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 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;
};
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With