Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Incomplete type" in class which has a member of the same type of the class itself

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

like image 849
Sterling Avatar asked Jun 14 '11 20:06

Sterling


People also ask

What is incomplete class type?

An incomplete class declaration is a class declaration that does not define any class members. You cannot declare any objects of the class type or refer to the members of a class until the declaration is complete.

Is an incomplete type?

An incomplete type is a type that describes an identifier but lacks information needed to determine the size of the identifier. An incomplete type can be: A structure type whose members you have not yet specified. A union type whose members you have not yet specified.

Can a class have itself as a member?

No, because the object would be infinitely large (because every Node has as members two other Node objects, which each have as members two other Node objects, which each... well, you get the point).


1 Answers

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; }; 
like image 52
ereOn Avatar answered Sep 22 '22 00:09

ereOn