Sign in to follow this  
Gumgo

Headers relying on each other...

Recommended Posts

Gumgo    968
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.

Share this post


Link to post
Share on other sites
Driv3MeFar    1080
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;
}

Share this post


Link to post
Share on other sites
Agony    3452
Then you include the header with the complete details in the source file where the function call is made.

A.h
#ifndef A_H
#define A_H

class B;

class A
{
public:
void DoSomething(B* b);
void DoSomethingElse();
};

#endif

B.h
#ifndef B_H
#define B_H

class 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();
}

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this