I'm having difficulty compiling a program. I have two classes defined and each class contains an object of the other class. For instance:
class A
{
public:
....
B ObjectB;
};
class B
{
public:
....
A ObjectA;
};
I don't get an error for the class B containment when I put the class A definition before it, but I do get errors for class A as it thinks that class B is undefined (since it comes later in the code). Any simple way to work around this issue (maybe something like a "class prototype" similar to function prototypes)?
Hmmm strange. I swear I tried the class prototyping and it didn't work.
I'm extending the OpenSteer application, and the particular file I'm extending has the two classes fully defined in the .cpp files (no .h files). Does that change anything with regards to dealing with the cyclic-dependency problem? And I assume I should put both class prototypes before both class definitions (at the very top of the generic example I gave in my previous post).
You can't include an instance of A inside B, because A contains an instance of B, which would then contain an instand of A. This would go on forever, like infinite recursion.
To solve this problem, you need to change either ObjectA or ObjectB or both into a reference or a pointer, e.g:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
class B;
class A
{
public:
B* PtrB;
};
class B
{
public:
A* PtrA;
};
A a;
B b;
a.PtrB = &b;
b.PtrA = &a;
...or with ObjectB being a reference, and ObjectA being an pointer...
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
class B;
class A
{
public:
// Must have constructor when using a reference member
A(B& b) : ObjectB(b) {}
B& ObjectB;
};
class B
{
public:
// Recommended to have constructor to initialize pointer
B() { PtrA = new A(*this); }
A* PtrA;
};