An object of the same type as the class

In C ++, as I have an object as the same type as its containing class, for example:

class Test { public: private: Test t; }; 
+4
source share
3 answers

The short answer is, you cannot.

You may have a pointer to an object of the same type, but not to the object itself.

If you NEED to do this (i.e.) cannot use a pointer, your design is probably incorrect. If you can use a pointer, use it.

Some reasons:

You will need to create an object when creating the instance, which means an infinite recursive call to the constructor.

What will be the sizeof() for the object?

+3
source

You cannot do this, as this will require infinite recursion. (Your t will contain another t , so you will have tttttttt... ad infinitum). What you could do is put a pointer to another object inside, for example.

 private: Test *t; 

The problem is that when you write:

 Test t; 

The compiler must know the size of Test in order to provide sufficient memory. The moment you wrote Test t; , this size is unknown because the compiler did not see the end of the Test definition (ie ; after closing } ) and therefore cannot determine its size.

+2
source

This is not possible . In max. You can have a link or pointer of the same class inside it.

 class Test { private: Test *t; }; 

As a side note, static objects are allowed. This is due to the fact that they are not actually associated with any particular instance of the class object. i.e:.

 class Test { private: Test t; // error static Test st; // ok! }; // define 'st' in the translation unit 
+1
source

All Articles