samedi 11 juillet 2020

Size of Class with virtual inheritnce

I was trying the below program on virtual inheritance with the https://www.onlinegdb.com/online_c++_compiler ..

#include <iostream>

using namespace std;

class ABase{ 
        int iMem; 
}; 
 
class BBase : public virtual ABase { 
        int iMem; 
}; 
 
class CBase : public virtual ABase { 
        int iMem; 
}; 
 
class ABCDerived : public BBase, public CBase { 
        int iMem; 
}; 

int main()
{
    cout << "Int is :" << sizeof(int) <<endl;
    cout << "Abase is :" << sizeof(ABase) << endl;
    cout << "Abase is :" << sizeof(BBase) << endl;
    cout << "Abase is :" << sizeof(CBase) << endl;
    cout << "Abase is :" << sizeof(ABCDerived) << endl;
    return 0;
}

The sizes of the ABase, BBase, CBase and ABCDerived are 4, 16, 16 and 40 respectively.

Normally from what i read i expect BBase and CBase to be 12 Bytes (8 bytes for the two int variables and 4 bytes for the vPtr). But i get 16, even if i assume that vPtr is using 8 Bytes, howcome ABCDerived is of 40 bytes size?

The OnlineGBD tool claims to use the G++/C++ compiler.

I know similar questions have been asked in this forum previously, but i am not able to understand this size calculation.

Aucun commentaire:

Enregistrer un commentaire