Sample code in C++:
class A {
public:
A(int) {}
};
class B : public virtual A {
public:
B(int b) : A(b) {}
};
class C : virtual public A {
public:
C(int c) : A(c) {}
};
class D : public B, public C {
public:
D() : B(1), C(2){};
};
This is typical code(solution) for diamond problem. I am aware why virtual keyword is used. But the internal mechanism by which the compiler takes care of the issue is not known to me. Now I have come across two different theories about the said mechanism which are as stated below.
When a class is inherited with virtual keyword, compiler adds a virtual base pointer in the derived class. I have checked the size of the derived class and yes it includes the size of an additional pointer. But I don't know where it points to and how does it work when a member of class A is referred in class D in the above example.
For each of the constructors compiler creates two versions of each definition provided by the programmer. Got to know from this link e.g. in the above code. Compiler will generate 2 versions of the constructor of C
C(int){} // Version1 C(int):A(int){} // Version2
And two different versions of constructor B
B(int){} // Version1 B(int):A(int){} // Version2
So when D is constructed then compiler will generate either of the below codes
D() : B(), C(2) {} // Version1 D() : B(1), C() {} // Version2
So as to make sure that only one instance of A is created and hence duplicate copy of A is avoided.
Please help me to understand the internal mechanism.