previous definition of a class

May 27, 2009 at 7:41pm
Hey Guys,
In my program I have two classes in two different header files. Each class has a pointer to the other class in it, so when I include the header in each file I get an error stating there's a previous definition of the class. Is there a way around that? Possibly with #ifndef?
May 27, 2009 at 7:50pm
forward declare the classes rather than include the headers.
May 27, 2009 at 8:03pm
Ok, now it's giving me an error for a forward declaration. Here is an example.

user.cpp:6: error: invalid use of incomplete type 'struct Account'
define.h:60: error: forward declaration of 'struct Account'

So what is the difference between needing a forward declaration and needing a header file? I'm self-taught, so forgive me ignorance. :-\
May 27, 2009 at 8:16pm
Also remember to use include guards on your headers.

1
2
3
4
5
6
7
8
9
10
#ifndef _MYHEADER_H_
#define _MYHEADER_H_

class AnotherClass;

class Class {
    AnotherClass* ac;
};
#endif

May 27, 2009 at 8:21pm
Ok, after some research I've found that adding headers into the .cpp files and using forward declarations in the headers is the best way to go. Does that sound right?
May 27, 2009 at 8:22pm
closed account (S6k9GNh0)
Header guards should work. If your not sure why they work it's simple: When you define something it's defined in your compiler. If it checks for that defined object again and it's already defined it will not include the remainder of the file.
May 27, 2009 at 8:25pm
I have header guards in all my headers. I never knew why they were necessary but I used them. :-\
Topic archived. No new replies allowed.