Redefinition error with multiple derived classes in the main
Asked Answered
P

3

5

I have an Object base class, and I have several derived classes called Item, Person, and Location.

Because each of these are derived from Object I need to include Object.h in each of their header files, and I include all of the derived classes in my main.

Because I am doing that I am getting a redefinition error.

What I want to know is what is the correct way to include these files to avoid this error?

Thanks!

EDIT:

object.h

using namespace std;

class Object{
    string name;
    string description;

    public:
        Object();
        Object(string name, string description);
        void set_name(string name);
        void set_description(string description);
        string get_name();
        string get_description();
        ~Object();
};

item.h

using namespace std;

#include "object.h"

class Item : public Object{
    public:
        Item();
        Item(string name, string description);

};

locale.h

using namespace std;

#include "object.h"

class Locale : public Object{
    public:
        Locale();
        Locale(string name, string description);
};

main.cpp

#include <iostream>
#include <string>

#include "locale.h"
#include "item.h"


using namespace std;

int main(){
    return 0;
}
Perron answered 26/2, 2012 at 21:3 Comment(5)
What is the exact error message? And please show a (simplified) version of your code.Budworth
The exact error message is "Redefinition of Object"Perron
Ok, you'll need to show some code. Check out sscce.org first (it's about boiling your code down to the best possible format for Stack Overflow).Budworth
I know what is causing the error. object.h is getting defined twice. I want to know what the correct format for including header files is for this circumstance.Perron
Please do not import namespaces inside header files - this is a pretty invasive thing to do, every file that includes that header will automatically import the whole namespace.Elnoraelnore
E
8

Strange, everybody I've met that hits this problem does not have a slightest idea what is going on and you have properly analysed the problem.

Read this: http://en.wikipedia.org/wiki/Include_guard

Elnoraelnore answered 26/2, 2012 at 21:6 Comment(0)
M
8

You should add include guards to your headers. This prevents headers from being included twice. For example, at the the top of the Object.h header, you would put,

#ifndef _OBJECT_H
#define _OBJECT_H

and then you end the header with,

#endif

If the header has already been included, the text between #ifndef and #endif is dropped.

Mccandless answered 26/2, 2012 at 21:8 Comment(0)
S
4

If you haven't got them in place already, you need to put include guards into you header files to prevent including the same files multiple times (which would redefine the classes).

Strudel answered 26/2, 2012 at 21:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.