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)'

有帮助吗?

解决方案

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()

其他提示

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top