0

Here is my code:

#include <iostream>
using namespace std;
class MyClass{
    int mem1;
    float mem2;
};
class MyKids: public virtual MyClass{
    int cmem1;
    int cmem2;
};
class MyLawKids:public virtual MyClass{
    int lmem1;
};
class MyGrands:public MyKids, public MyLawKids{
    int gmem1;
};

int main(){
    cout << "\n Size of MyClass: " << sizeof(MyClass) << " bytes" << endl ;
    cout << " Size of MyKids: " << sizeof(MyKids) << " bytes" << endl ;
    cout << " Size of MyLawKids: " << sizeof(MyLawKids) << " bytes" << endl ;
    cout << " Size of MyGrands: " << sizeof(MyGrands) << " bytes" << endl ;
    return 0;
}

Result:

 Size of MyClass: 8 bytes
 Size of MyKids: 20 bytes
 Size of MyLawKids: 16 bytes
 Size of MyGrands: 32 bytes

Process returned 0 (0x0)   execution time : 0.094 s
Press any key to continue.

I think the size of MyGrands class its should be 36 bytes = (sizeof(MyKids + MyLawKids + int gmem1) - 4 bytes of virtual table pointer).

Why my result shown me "Size of MyGrands: 32 bytes" ?

  • https://stackoverflow.com/questions/119123/why-isnt-sizeof-for-a-struct-equal-to-the-sum-of-sizeof-of-each-member (padding is involved, different compiler or platform may result in different results) – Alessandro Teruzzi Jun 06 '18 at 08:49
  • Virtual inheritance, multiple inheritance you could (probably) do without. – Ron Jun 06 '18 at 09:08
  • btw the difference in size you observe is just a consequence of what virtual inheritance is made for. Any article on virtual inheritance should contain an explanation of the effect you see – 463035818_is_not_an_ai Jun 06 '18 at 09:16

1 Answers1

2

MyGrands contains only one instance of MyClass due to MyKids and MyLawKids inheriting virtually from MyClass. Hence your calculation is wrong, by double counting the size of MyClass. By the way, in general you should not rely on a naive addition of the pieces being the same as the size of the whole. The compiler can add padding.

463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185