To
declare and not
define a class, just say
class class_name.
|
class person; // no member specification (class body)
|
Because the size and member layout of
person isn't known,
person is an
incomplete type until it's defined later:
1 2
|
// incomplete class type person is completed by this class definition
class person { int foo; };
|
Before
person is complete, it isn't useful for very much. In particular, objects of type
person cannot be created until the type is completed.
I have two classes that have each other as members |
This program is nonsense and won't compile, for the reasons discussed above:
1 2 3
|
struct A; // declares the incomplete class type A
struct B { A a; }; // error: class A has incomplete type
struct A { B b; }; // A is complete here
|
Also consider that if A contains B and B contains A, what is
sizeof (A)?
What you can do is store a pointer somewhere to break the cycle. The size and layout of
person isn't necessary to merely to create a pointer to it.
1 2 3 4
|
struct A;
struct B { std::unique_ptr<A> pa; ~B(); };
struct A { B b; };
B::~B() = default;
|
This is challenging to do correctly. Consider another way to represent the relationships between objects - for instance, with some kind of adjacency list.
What's the bigger picture?