class A { public: void eat(){ cout<<"A";} };
class B: virtual public A { public: void eat(){ cout<<"B";} };
class C: virtual public A { public: void eat(){ cout<<"C";} };
class D: public B,C { public: void eat(){ cout<<"D";} };
int main(){
A *a = new D();
a->eat();
}
I understand the diamond problem, and above piece of code does not have that problem.
How exactly does virtual inheritance solve the problem?
What I understand:
When I say A *a = new D();
, the compiler wants to know if an object of type D
can be assigned to a pointer of type A
, but it has two paths that it can follow, but cannot decide by itself.
So, how does virtual inheritance resolve the issue (help compiler take the decision)?
Actually the example should be as follows:
... that way the output is gonna be the correct one: "EAT=>D"
Virtual inheritance only solves the duplication of the grandfather! BUT you still need to specify the methods to be virtual in order to get the methods correctly overrided...