2

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

3
  • 1
    You are experiencing what is known as the Diamond Inheritance Problem.. en.wikipedia.org/wiki/Multiple_inheritance#The_diamond_problem Commented Jan 18, 2014 at 10:37
  • 1
    That fact that you try to call that specific function doesn't fix the D class itself. Commented Jan 18, 2014 at 10:40
  • 1
    @OP, I just thought I'd point this out.. main in C and C++ is NEVER void. Please change it to return int. It really bothers me seeing this. Commented Jan 18, 2014 at 10:53

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.