Headers relying on each other...
I'm having a problem with headers...
Say I have header A and header B. Header A declares class A and header B declares class B.
Class A has a pointer to class B. Class B has a pointer to class A.
Therefore, header A includes header B and header B includes header A.
And of course, in each header, there is an #ifndef... #define... #endif so that the classes aren't declared twice.
Here's the problem:
The compiler starts with header A. Since A_DEFINED has not been defined, it is defined and the script compiles. The first thing it hits is #include "B.h", so the compiler moves on to B.h before continuing on A.h. At the beginning of B.h, the compiler hits the #ifndef B_DEFINED, and since B_DEFINED has not been already defined, the compiler continues. The next thing it hits is #include "A.h". The compiler moves to A.h, but hits #ifndef A_DEFINED again. Since A_DEFINED has been defined, it skips the rest of the file and resumes at B.h. Now it moves on to the class declaration in B.h. But suddenly it hits a line that says "A * newpointerA;". Since the first execution of A.h hasn't finished, and the second one was skipped because A_DEFINED had already been set, the compiler has not declared class A yet and runs into an error!
This is the problem I'm having, except slightly more extensive with several scripts that rely on each other. Is there any ways to sort this all out? Thanks.
Use forward declairations. If you're just storing pointers, then the compiler doesn't need to know the details of the class, just that there is a class of that name.
A.h:
class B;
class A
{
...
B *m_b;
}
B.h:
class A;
class B
{
...
A *m_a;
}
A.h:
class B;
class A
{
...
B *m_b;
}
B.h:
class A;
class B
{
...
A *m_a;
}
Then you include the header with the complete details in the source file where the function call is made.
A.h
B.h
A.cpp
B.cpp
A.h
#ifndef A_H#define A_Hclass B;class A{ public: void DoSomething(B* b); void DoSomethingElse();};#endif
B.h
#ifndef B_H#define B_Hclass A;class B{ public: void DoSomething(A* a);};#endif
A.cpp
#include "A.h"#include "B.h"void A::DoSomething(B* b){ b->DoSomething(this);}void A::DoSomethingElse(){}
B.cpp
#include "B.h"#include "A.h"void B::DoSomething(A* a){ a->DoSomethingElse();}
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement