Virtual methods in a virtual base class

Something that baffled me about inheriting a virtual base class ... Given the following classes:

class A { virtual void foo() = 0; } class B : virtual A { void foo() { /* do X */ } } class C : virtual A { void foo() { /* do Y */ } } class D : B, C { } 

Will it compile? If so, what will be the result of the following code:

 D d; A* a = &d; a->foo(); 
+8
c ++ methods multiple-inheritance virtual
source share
4 answers

It should not compile, the foo function will be ambiguous. Since A :: foo () is a pure virtual function, ambiguity must be removed.

+7
source share

It will not compile for three reasons, none of which has anything to do with virtual inheritance (well, maybe the last one).

  • You forgot the semicolons after class definitions

  • Your inheritance is closed

  • D::foo() ambiguous unless explicitly redefined

By the way, the definition of D itself is poorly developed, and not just the fact that you are trying to use it. I mean, if your main() function was empty, it still won’t compile.

And "Will it compile?" has the obvious answer "Why don't you try?"

Quote from the standard: 10.3.10

The following example shows a function that does not have a unique target interceptor:

  struct A { virtual void f(); }; struct VB1 : virtual A { // note virtual derivation void f(); }; struct VB2 : virtual A { void f(); }; struct Error : VB1, VB2 { // ill-formed }; 
+4
source share

It will not compile. GCC:

 error: no unique final overrider for 'virtual void A::foo()' in 'D' 

You could find it pretty quickly.

Same thing with icc:

 error #361: override of virtual function "A::foo" is ambiguous 
+4
source share

No, it will not be:

 diamond.cpp:24:7: error: request for member 'foo' is ambiguous diamond.cpp:13:8: error: candidates are: virtual void C::foo() diamond.cpp:8:8: error: virtual void B::foo() 

This is called the Diamond issue, see http://en.wikipedia.org/wiki/Diamond_problem

+3
source share

All Articles