This question already has an answer here:
- Can a c++ class include itself as an member? 4 answers
I read about structure in c++ that it can not contain instance of itself. Can anybody help me to understand why it can not contain instance of itself?
This question already has an answer here:
I read about structure in c++ that it can not contain instance of itself. Can anybody help me to understand why it can not contain instance of itself?
Because to create the instance of it, you will need to create the variable, which is itself an instance of it - which will invoke the constructor.
This will result in infinite recursive call to the constructor.
Assume class A
has an instance variable named a
:
Invoking the constructor of A
will cause the initialization of a
, which is itself an A
. To do it - the constructor of A
will be invoked again.
Note that it will not even compile because the compiler cannot allocate the memory for it, it doesn't know how much space to allocate for each object. How much space does it take to store the instance variable a
? [Any finite space will not be enough because there will always be an extra variable which also needs to be allocated]
Because then it would take up "infinite" storage since when it is initialised it recursively initialises itself. You can store pointers to the same structure, however.
e.g. This is invalid:
struct a
{
int someVar;
a bad;
};
This is valid (say if you want a linked list of this structure):
struct a
{
int someVar;
a* good;
};
struct bedroom
{
bed b;
table t;
bedroom r;
};
Do you see the problem now? A bedroom would need storage for an infinite amount of beds and tables.
Because then it would lead to inifite recursion. e.g.
struct foo
{
int boo;
foo f;
};
foo f;
foo
would contain a foo
which contains a foo
etc...
To get around it you should use a pointer:
struct foo
{
int boo;
foo* f;
};
not just structure any incomplete data type cannot be used with in it. lets say u have a structure A and u have included the same structure as a member,now when compiler tries to allocate memory to it how does it know how much to allocate because u have declared structure A inside it which is not yet completely defined and it will throw an error incomplete data type not allowed.
As other answers point out, the structure cannot contain an instance of itself, because that would result in an infinite recursion when creating the structure. However a structure can contain a pointer to itself:
struct foo
{
int boo;
foo *f;
};
foo f;
f.f = &f;
Because it is impossible to create memory layout for such structure. If a struct foo
contains an int
and a foo
, how would you fit sizeof(int)+sizeof(foo)
bytes into sizeof(foo)
bytes? The equation A+B=A
does not have any solutions for A,B > 0
.