#include <iostream>
using namespace std;
class A { public: void eat(){ cout<<"A";} };
class B: public A { public: void eat(){ cout<<"B";} };
class C: 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 am not sure this is called diamond problem or not, but why doesn’t this work?
I have given the defination for eat() for D. So, it doesn’t need to use either B‘s or C‘s copy (so, there should be no problem).
When I said, a->eat() (remember eat() is not virtual), there is only one possible eat() to call, that of A.
Why then, do I get this error:
‘A’ is an ambiguous base of ‘D’
What exactly does A *a = new D(); mean to the compiler??
and
Why does the same problem not occur when I use D *d = new D();?
Imagine a slightly different scenario
If this would work, would it increment the
ainBor theainC? That’s why it’s ambiguous. Thethispointer and any non-static data member is distinct for the twoAsubobjects (one of which is contained by theBsubobject, and the other by theCsubobject). Try changing your code like this and it will work (in that it compiles and prints “A”)That will call
eaton theAsubobject ofBandCrespectively.