Reputation: 1814
I have two classes:
Class A and Class B
Class A is declared under namespace Common::subnamespace1
Class B is declared under namespace Common::subnamespace2
Both class A and B are under namespace Common but under different sub namespaces.
My problem is as follows:
Including the class A inside class B header file is OK But including class B header in class A and declaring a member of type class B in it causes compilation error undefined type 'B'.
I have tried with forward declarations to avoid cyclic dependency. But still error exists.
Actually I am very confused in what order I have to use the inclusions.
NB: I am not posting the code since I just want to know the exact order or method of declaring or including classes in each other.
Any help will be appreciated.
Upvotes: 0
Views: 749
Reputation: 24626
#include
the other class' definition into the header if you use that class as base class or as member variable or if you use it inside an inlined function in the header (including compiler generated special members). For your case, I assume that the definition of A is needed for B, but not the other way round. You headers should look like this then:
A.h:
namespace Common {
namespace subnamespace2 {
class B;
}
namespace subnamespace1 {
class A {
void foo(subnamespace2::B& b); //reference, parameter -> fwd-decl
subnamespace2::B* pB; //pointer -> fwd-decl
};
}
}
B.h:
#include "A.h"
namespace Common {
namespace subnamespace2 {
class B {
subnamespace1::A a; //direct member -> def needed
void bar() {
a.foo(*this); //inline use -> def needed
}
};
}
}
Upvotes: 1