I understand that diamond-based inheritance is ambiguous and can be avoided by using inheritance through virtual Base Classes , thatβs not the point. The question is about the size of the most derived class in hierarchical form when the classes are polymorphic. The following is an example code and an output example:
#include<iostream> using namespace std; class Base { public: virtual void doSomething(){} }; class Derived1:public virtual Base { public: virtual void doSomething(){} }; class Derived2:public virtual Base { public: virtual void doSomething(){} }; class Derived3:public Derived1,public Derived2 { public: virtual void doSomething(){} }; int main() { Base obj; Derived1 objDerived1; Derived2 objDerived2; Derived3 objDerived3; cout<<"\n Size of Base: "<<sizeof(obj); cout<<"\n Size of Derived1: "<<sizeof(objDerived1); cout<<"\n Size of Derived2: "<<sizeof(objDerived2); cout<<"\n Size of Derived3: "<<sizeof(objDerived3); return 0; }
The output I get is:
Size of Base: 4 Size of Derived1: 4 Size of Derived2: 4 Size of Derived3: 8
As I understand it, Base contains a virtual member function and therefore sizeof Base = size vptr = 4 in this environment
The classes Derived1 and Derived2 .
Here are my questions related to the following scenario:
What about the size of an object of class Derived3 , does this mean that class Derived3 has 2 vptr?
How does the Derived3 class work with these 2 vptr, any ideas on the mechanism it uses?
The sizeof classes are left as a part of the compiler implementation and are not defined by the standard (since the virtual mechanism itself is a detail of the compiler implementation)?
source share