"Incomplete type" in class which has a member of the same type of the class itself
Solution 1:
At the time you declare your member, you are still defining the A
class, so the type A
is still undefined.
However, when you write A*
, the compiler already knows that A
stands for a class name, and so the type "pointer to A" is defined. That's why you can embed a pointer to the type your are defining.
The same logic applies also for other types, so if you just write:
class Foo;
You declare the class Foo, but you never define it. You can write:
Foo* foo;
But not:
Foo foo;
On another hand, what memory structure would you expect for your type A
if the compiler allowed a recursive definition ?
However, its sometimes logically valid to have a type that somehow refer to another instance of the same type. People usually use pointers for that or even better: smart pointers (like boost::shared_ptr
) to avoid having to deal with manual deletion.
Something like:
class A
{
private:
boost::shared_ptr<A> member;
};
Solution 2:
This is a working example of what you are trying to achieve:
class A {
public:
A() : a(new A()) {}
~A() { delete a; a = nullptr; }
private:
A* a;
};
A a;
Happy Stack Overflow!
Solution 3:
A
is "incomplete" until the end of its definition (though this does not include the bodies of member functions).
One of the reasons for this is that, until the definition ends, there is no way to know how large A
is (which depends on the sum of sizes of members, plus a few other things). Your code is a great example of that: your type A
is defined by the size of type A
.
Clearly, an object of type A
may not contain a member object that is also of type A
.
You'll have to store a pointer or a reference; wanting to store either is possibly suspect.
Solution 4:
A simple way to understand the reason behind class A
being incomplete is to try to look at it from compiler's perspective.
Among other things, the compiler must be able to compute the size of A
object. Knowing the size is a very basic requirement that shows up in many contexts, such as allocating space in automatic memory, calling operator new
, and evaluating sizeof(A)
. However, computing the size of A
requires knowing the size of A
, because a
is a member of A
. This leads to infinite recursion.
Compiler's way of dealing with this problem is to consider A
incomplete until its definition is fully known. You are allowed to declare pointers and references to incomplete class, but you are not allowed to declare values.