I have a class that should have a private member of the same class, something like:
class A {
private:
A member;
}
But it tells me that member is an incomplete type. Why? It doesn’t tell me incomplete type if I use a pointer, but I’d rather not use a pointer. Any help is appreciated
At the time you declare your member, you are still defining the
Aclass, so the typeAis still undefined.However, when you write
A*, the compiler already knows thatAstands 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:
You declare the class Foo, but you never define it. You can write:
But not:
On another hand, what memory structure would you expect for your type
Aif 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: