I don't understand why 'Derived1' requires the same amount of memory as 'Derived3'

  • A+

In the following code I don't understand why 'Derived1' requires the same amount of memory as 'Derived3'. Also is there any specific significance of size of Derived 4 being 16.

#include <iostream> using namespace std;  class Empty {};  class Derived1 : public Empty {};  class Derived2 : virtual public Empty {};  class Derived3 : public Empty {         char c; };  class Derived4 : virtual public Empty {     char c; };  class Dummy {     char c; };  int main() {     cout << "sizeof(Empty) " << sizeof(Empty) << endl;     cout << "sizeof(Derived1) " << sizeof(Derived1) << endl;     cout << "sizeof(Derived2) " << sizeof(Derived2) << endl;     cout << "sizeof(Derived3) " << sizeof(Derived3) << endl;     cout << "sizeof(Derived4) " << sizeof(Derived4) << endl;         cout << "sizeof(Dummy) " << sizeof(Dummy) << endl;      return 0; } 

The output of this code gave was:

sizeof(Empty) 1 sizeof(Derived1) 1 sizeof(Derived2) 8 sizeof(Derived3) 1 sizeof(Derived4) 16 sizeof(Dummy) 1 


A class must have a sizeof of 1 or greater otherwise pointer arithmetic would break horribly, and the elements of array of that class would all occupy the same memory.

So sizeof(Derived1) is at least 1, as is sizeof(Empty). Empty base optimisation means that the size of the derived class is effectively zero.

sizeof(Derived3) can also be 1, since the single member is a char. Note that the compiler is again exploiting empty base optimisation here.

The polymorphic classes (i.e. those containing virtual keywords), have larger sizes due to your compiler implementing the requirements for polymorphic behaviour.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: