I'm assuming that my base class has one "int" member and the derived class has also one "int" member. Now when I create one derived class object and see the output by sizeof(derivedClassObject) then it is becoming 8. Now I am troubling to grasp the underlying idea here.
I know that when I create an object for the derived class then both the base class constructor and derived class constructor are get called. The only purpose of base class constructor here is to initialize the base class data members. I expected that the sizeof will display 4 because I am only interested to create a derived class object. But instead of that I am getting output as "8". So, extra 4 byte is being allocated and I think its happening for the base class constructor. I would appreciate if anyone help me to grasp the following concepts:
- Why 8 bytes are being allocated instead of 4 when I create a derived class object? Does it mean that base class constructor is also creating a new base class object and concatenating it with the new derived class object?
I am just creating one derived class object and the size of that derived class object is: sizeof(baseClassObject) + sizeof(derivedClassObject). I would really appreciate to get some help.
Assume you have two classes as below
Now I go ahead and create an object of Audi
you can do something like
If your assumption that creating the derived class should allocate space only for derived members, where would 'make' be stored in this case?
A derived class is nothing but baseclass + members declared in derived class. Hence your derived object would look something like this in memory
Hence you get the size of derived class members plus size of base class. Again, size of base class will be size of base class members plus size of its base class. Hope this helps!
In general
inheritance
in oop means that an object of a derived class is also an object of the base class. Therefore it contains everything the base class contained (in this case one int, so 4 byte) and any additional data members from the derived class (so another int).If that wasn't the case, how would an object of the derived class be usable as an object of the base class? Inherited methods would likely do horrible things, since the data members they are trying to access wouldn't exist.
Therefore the
sizeof(derivedClass)==sizeof(baseClass) + sizeof(int)
(although nothing is keeping the compiler from making it bigger).If you don't want your
derivedClass
to be usable as abaseClass
you shouldn't derive from it.