Circular reference

Hi,

I don't know how to avoid circular reference. Classe B need a object of class C and C one of B?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

#include B.h
Class A
{
}

#include C.h
Class B
{
}

include B.h
Class C
{
}
Class B need a object of class C and C one of B?

They can't actually contain each other, but they can have pointers or references to each other.

To see why this is, consider how big C and B would have to be if they could contain each other. An instance of C would have to be at least as big as B, since it contains a B. But an instance of B would have to be at least as big as C since it contains a C. They would each have to be infinitely large to contain the other.

To deal with the circular reference, you do a forward declaration:

file B.h:
1
2
3
4
5
class C;  // forward declaration

class B {
    C *cp;
};

file C.h:

1
2
3
4
5
class B;  // forward declaration

class C {
    B *bp;
};

I mean a instance of each other
Please show your current definitions of B and C.
Ok with the forward declaration.

Thank
Last edited on
You want to create object of type C. It has one B object inside. That B has one C object inside. That C has one B object inside. That B has one C object inside. That C has one B object inside. ...

You can't have infinite recursion.

You have to rethink your design.
Topic archived. No new replies allowed.