views:

79

answers:

2

Suppose I have a class A and a class B.

The .h of A, needs the .h of B, and the .h of B needs the .h of A. (need = #include).

All .h have the guards:

#ifndef _classX_
#define _classX_
...
...
#endif

But if I compile the .cpp of A, then when it includes the .h of B, the B class cannot include the .h of A class because the A class has already use the guard.

How can i solve this?

+5  A: 

You will need a forward declaration of one of the classes.

// a.h
// do not #include b.h

class B;    // forward declaration

class A {
    ....
    B * b;
};

Note that the class A cannot contain an actual B instance - it must be a pointer or a reference. You also cannot call any functions via the B pointer in the header - they will have to go in a .cpp source file which #includes both headers.

anon
+3  A: 

One of them need to get around not to include it. For many cases this is possible such that you can move the #include into the .cpp file

class A {
  // no need for header of B here
  void f(B b);

  // no need for header of B here either
  B *b;
};

Generally for the function declarations whose definitions are in the .cpp files, you don't need any #includes in the header. For class members you only need headers if you want to have them as value objects embedded. You need to change those to pointers (or smart-pointers) and new them within the .cpp file in that case. For the compiler to know what B is in my above example, you just need to put a forward declaration before the definition of A like this:

class B;
Johannes Schaub - litb
Also, your include guards shouldn't have leading underscores. Those are reserved for use by compiler implementers and/or system use.
George