I have tried to solve the problems related to circular dependency in some files I have made following that structure:
A.h
#include "B.h"
#include "C.h"
#include "D.h"
namespace NS {
class B;
class C;
class D;
class A {
/* ... */
A(const A& a) {};
A(const B& a) {};
A(const C& a) {};
A(const D& a) {};
/* ... */
};
}; // NS END
B.h
#include "A.h"
#include "C.h"
#include "D.h"
namespace NS {
class A;
class C;
class D;
class B {
/* ... */
B(const B& a) {};
B(const A& a) {};
B(const C& a) {};
B(const D& a) {};
/* ... */
};
}; // NS END
C.h
#include "A.h"
#include "B.h"
#include "D.h"
namespace NS {
class A;
class B;
class D;
class C {
/* ... */
C(const C& a) {};
C(const A& a) {};
C(const B& a) {};
C(const D& a) {};
/* ... */
};
}; // NS END
D.h
#include "A.h"
#include "B.h"
#include "C.h"
namespace NS {
class A;
class B;
class C;
class D {
/* ... */
D(const D& a) {};
D(const A& a) {};
D(const B& a) {};
D(const C& a) {};
/* ... */
};
}; // NS END
Whatever I try I have some errors from the constructors taking as argument classes in other files, even putting the declaration ahead, seems like it take it the declaration as declaration and definition, and ignore the real definition that is in another file. How could I solve that?
NOTE: I have define guard in each file, just I didnt put it here
if you remove all the #includes in the headers and put them in the source files, everything should compile.
You don’t need the includes since you have forward declarations which is sufficient in this case since you only use const references to the forward declared classes. (note: previous statements only hold if your sample code mimics your actual code).
You can also add a seperate header forward.h containing the declarations, instead of repeating yourself everywhere:
Now make A.h, B.h etc
#include forward.hand you do not need the forward declarations in each header anymore.