2 ways of resolving ambigous inheritance of virtual method

Viewed 72

Following code is from MSDN, I copied the code here to avoid doing my own sample, basically I'm having this problem in my project.

struct V {
   virtual void vf();
};

struct A : virtual V {
   void vf() override;
};

struct B : virtual V {
   void vf() override;
};

struct D : A, B {
   // Uncomment the following line to resolve.
   // void vf() override;
};

I took a look at this SO Question where the suggestion is to use using directive to resolve ambiguous symbol.

That suggestion doesn't work for this sample, instead to resolve the problem we should explicitly override base methods in derived class.

I would like to avoid explicitly override in derived class, so the question is, why cant this be resolved with using directive as suggested in SO link above, instead of overriding? for example:

struct D : A, B {
   using A::vf(); // not going to work
};

The reason why to avoid explicit override is to make use of method code in one of the base classes.

2 Answers

In your case, I think you have to give an explicit override to resolve the ambiguity! However, it would be an extremely trivial override:

struct D : A, B {
    // Uncomment the following line to resolve.
    void vf() override { A::vf(); }
};

This will just call the A base class whenever D::vf() is called! Thus, in accordance with your last sentence, there is no problem, as the "method code in one of the base class" is used (but you have to specify which base class).

using simply resolves which method you mean to call, in this case.
D still needs to be a complete object and must have a final overrider for vf regardless of resolve helpers.
If vf was not implemented in the base class, then using would suffice, as the type is complete and all you need to do is resolve the correct call.

Related