Reputation: 83
In c++ how do I have an object as the same type as its containing class eg:
class Test
{
public:
private:
Test t;
};
Upvotes: 4
Views: 107
Reputation: 88711
You can't do that, since it would require infinite recursion. (Your t
would contain another t
, so you'd have t.t.t.t.t.t.t.t....
ad infinitum). What you could do though is put a pointer to another object inside, e.g.
private:
Test *t;
The problem is that when you write:
Test t;
The compiler needs to know the size of Test
in order to provide sufficient storage. At the point where you wrote Test t;
that size isn't known because the compiler hasn't seen the end of the definition of Test
(i.e. the ;
after the closing }
) and thus can't determine the size of it.
Upvotes: 2
Reputation: 69988
That's not possible. At the max you can have a reference or pointer of the same
class
within it.
class Test
{
private:
Test *t;
};
As a side note, static
objects are allowed. This is because, they are not actually bound with any particular instance of class
object. i.e.:
class Test
{
private:
Test t; // error
static Test st; // ok!
}; // define 'st' in the translation unit
Upvotes: 1
Reputation: 258568
Short answer, you can't.
You can have a pointer to an object of the same type, but not an object itself.
If you NEED to do this (i.e.) can't use a pointer, your design is probably wrong. If you can use a pointer, use it.
Some reasons:
You'd have to create the object on instantiation, that means an infinite recursive call on the constructor.
What would the sizeof()
for the object be?
Upvotes: 3