Question

In C++ multiple inheritance with virtual base i understand why could this code be ambiguous , but why it still complains when i specifically call a derived class method ?

class A {
public:
    virtual void f() { cout << 1 ;}
};
class B :virtual public A {
public:
    virtual void f() { cout << 2; }
};
class C :virtual public A {
public:
    virtual void f() { cout << 3; }
};
class D : public B, public C {};

void main(){
    D* d = new D();
    d->B::f();
    getch();
}

i would expect that it will run the B:f() method but i get : "ambiguous inheritance of 'void A::f(void)'

Was it helpful?

Solution

The problem is that your function is virtual which means it overrides address in vtable. You can't override one address with two functions. Without virtual qualifier there would be just ambiguity during the call which can be avoided just like you did specifying base class B::f()

OTHER TIPS

The problem is that your class D has two final overriders of function f. See http://en.cppreference.com/w/cpp/language/virtual about final overrider.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top