Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why structure can not contain Instance of itself? [duplicate]

Tags:

c++

structure

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?

like image 716
Learner Avatar asked Nov 29 '22 03:11

Learner


2 Answers

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;
};
like image 90
Alex Z Avatar answered Dec 05 '22 11:12

Alex Z


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]

like image 26
amit Avatar answered Dec 05 '22 10:12

amit