I understand that the Diamond shaped inheritance causes ambiguity and it can be avoided by using inheritance through virtual Base Classes
, the question is not about it. The question is about sizeof the most derived class in a diamond shaped hierarchy when the classes are polymorphic. Here is a sample code and the sample output:
#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 Base
contains a virtual member function and hence,
sizeof Base = size of vptr = 4 on this environment
Similar is the case Derived1
& Derived2
classes.
Here are my questions related to above scenario:
How about size of a Derived3
class object, Does it mean Derived3 class has 2 vptr?
How does the Derived3
class work with these 2 vptr, Any ideas about the mechanism it uses?
The sizeof classes is left as implementation detail of compiler & not defined by the Standard(as the virtual mechanism itself is an implementation detail of compilers)?
sizeof
is an implementation details too, it notably depends on pointer size, if you were on a 64 bits platform, you would be seeing8/8/8/16
. – Matthieu M.