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;
}
Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
jasonaburton
  • 2,941
  • 7
  • 34
  • 48

3 Answers3

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

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.

Michael Morgan
  • 816
  • 5
  • 6
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).

Timo Geusch
  • 24,095
  • 5
  • 52
  • 70