-1

Please consider this example:

#include <bits/stdc++.h>
using namespace std;

class Example{

    private:
        int var1;
        Example *oak;
};

is alright but not this

#include <bits/stdc++.h>
using namespace std;

class Example{
    private:
        int var1;
        Example oak;
};

Why having a pointer to the same class object as member variable is okay but not the class object itself as a member variable?

Can you give me some practical cases where having a same class object as member variable is useful?

hulk_baba
  • 87
  • 1
  • 9
  • What would be the size of the second type? In C++, every type has a size. An int might be 4 bytes, a pointer may also be 4 bytes. In the second example, the size of `Example` would have to be `sizeof(Example) = 4 + sizeof(Example)`. That's an equation with no solution. In the first example, you have `sizeof(Example) = 4 + sizeof(Example*) = 4 + 4 = 8` (as an example for some targets) – Justin Jul 23 '17 at 05:23
  • 2
    You can't store an aeroplane (of the same model) in the cargo bay of an aeroplane... but you could store a note saying where to find another aeroplane – M.M Jul 23 '17 at 05:29

2 Answers2

0

You would have an infinite object definition loop. How do you think you are going to stop defining oak instances?

You need to create the pointer explicitly, so you have the control of creation.

seleciii44
  • 1,529
  • 3
  • 13
  • 26
0

well, you are right a class can't have an object of its own that is because if we do so the compiler won't be able to calculate the size of the object as it will go in an infinite loop. For example: I initialized an object in the main() object will contain another object that another object will contain another and compiler won't be able to do calculate the size. But as we know a pointer has fixed size wheater it's pointing an int char or an object so the compiler will be able to calculate its size.