How to work around multiple/related containment issue

Hello,

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)?

Thanks!
Yes use class prototyping. This is called "cyclic-dependency".

Inside each of your .h files put

class A; // (or B)

and do NOT put the #include. You put the #include into the .cpp file.
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).
I think just "Forward Declaration" will not solve this problem.

As While compiling the class's size plays an important role.

Class A contains an object of Class B, So the size of class B is needed, while compiling class A.
Same for Class B also.

I don't know how to solve this and waiting for the same.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
using namespace std;

class B;

class A
{
public:
	B ObjectB;
};

class B
{
public:
	A ObjectA;
};

int main()
{
	return 0;
}


The compilation error of above is:

containment.cpp(9) : error C2079: 'ObjectB' uses undefined class 'B'
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;
};
Topic archived. No new replies allowed.