Bloomberg LP Interview Question
Software Engineer / DevelopersOther things that would add up to what harish said are
1. virtual functions-4 bytes of virtual table pointer will be added.
if base class A has a virtual function and a class variable of type char the sizeof(A's obj) is sizeof(Vptr)+sizeof(char).
if there exists a derived class Class B:public Class A with another virtual function and class variable of int type. sizeof(B's obj)=sizeof(A)+sizeof(int). It wil just change the Vptr to point to its virtual function table, it will not allocate another 4bytes for its virtual function rather use one derived from base class.
2. Mode of inheritance
courtesy: cprogramming.com
In C++, sometimes we have to use virtual inheritance for some reasons. (One classic example is the implementation of final class in C++.) When we use virtual inheritance, there will be the overhead of 4 bytes for a virtual base class pointer in that class.
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;
};
And if you check the size of these classes, it will be:
* Size of ABase : 4
* Size of BBase : 12
* Size of CBase : 12
* Size of ABCDerived : 24
Because BBase and CBase are dervied from ABase virtually, they will also have an virtual base pointer. So, 4 bytes will be added to the size of the class (BBase and CBase). That is sizeof ABase + size of int + sizeof Virtual Base pointer.
Size of ABCDerived will be 24 (not 28 = sizeof (BBase + CBase + int member)) because it will maintain only one Virtual Base pointer (Same way of maintaining virtual table pointer).
Explanation for mode of inheritance:
now for sizeof(ABCDerived)
size of its iMem(4)+
size of its base classes with only one version of Vptr ie(BBase: size of(B's iMem)+sizeof(A)= 4+4) +CBase: size of(C's iMem)+sizeof(A)= 4+4) + 4 (Vptr )
shouldn't the size of ABCDerived be =(sizeof(BBase)-sizeof(ABase)-sizeof(ABase virtual table)) + (sizeof(CBase)-sizeof(ABase)-sizeof(ABase virtual table)) + (sizeof(iMem from ABCDerived)+sizeof(ABase)+sizeof(ABase virtual table)) = 4 + 4 + 12 = 20
since ABCDerived is responsible for instantiating the class ABase and not the classes BBase and CBase?
learncpp.com/cpp-tutorial/118-virtual-base-classes/
*A derived class size also includes the size of the immediate base class/classes.
- Harish March 17, 2010+ size of all non-static members within the derived class.
+ Byte alignment may play a role