+ 2

Why we cannot create a object inside class?

class Sololearn { Sololearn *obj;// It is accepted Sololearn ob;//It is not accepted }; why?

14th Feb 2017, 3:25 PM
Balaji Rs
Balaji Rs - avatar
2 odpowiedzi
+ 2
Thank you Great Explanation
14th Feb 2017, 3:55 PM
Balaji Rs
Balaji Rs - avatar
+ 1
The pointer works since it is not pointing at anything yet. You have to instantiate a 'real' object at runtime, something like this: class S { S *obj; }; S c1; S c2; c1.obj = &c2; But note that c2's obj pointer is still uninitialized - it is not pointing at anything (yet). So now you can do: S c3; c2.obj = &c3; //Which is the same as c1.obj->obj And you can keep going like this as 'deep' as you want. But the main thing to grasp is that the 'deepest' S* obj is always uninitialized at first (not pointing at anything). But now compare it to this case: class S{ S ob; }; Even as part of the definition of the class it contains an instance of S (S::obj) which, in turn, contains an instance of s (S::obj::obj) which, in turn, contains an instance of S.... and so on - and we have infinite regress!
14th Feb 2017, 3:51 PM
Ettienne Gilbert
Ettienne Gilbert - avatar