Can a C++ class have an object of self type?
Depends on what is meant by "have an object".
Maybe the "this" pointer? Your question is a little broad, don't you think?
Wazza
well i dont.
i mean a class object as an instance of the same class.
No. An object type may not be recursive.
You can have a pointer or a reference to another instance of the container class.
What exactly are you trying to do? Perhaps we can suggest a good way to do it.
#include<iostream.h>
class Base
{
Base b;
};
int main(void)
{
Base b;
}
is this possible?
It is impossible because at the time when data member b is being declared type Base is not defined yet.
You can only do this:
1 2 3 4
|
class Base
{
Base* b;
};
|
But careful, if you do this, you'll have infinite recursion:
1 2 3 4 5 6
|
class Base
{
Base* b;
public:
Base() : b(new Base() ) {}
};
|
Duoas, I'm not sure how a reference would work. It could compile like this:
1 2 3 4 5 6
|
class Base
{
Base& b;
public:
Base(Base& in) : b(in) {}
};
|
But you'd never be able to make the first instance of it (unless perhaps it inherits from another class)
Last edited on
inception. it would be like a linked node/list. If it IS allocateable (non virtual)
@Stewbond: Base b(b);
compiles just fine (a name introduced by the declarator is visible in the initializer), although its legality is questionable.
@Stewbond: Base(): b(*this) {}