struct A {
virtual void foo() { std::cout << "a";};
};
struct B:public virtual A {
void foo() { std::cout << "b";}
};
struct C:public virtual A {
void foo() { std::cout << "c";}
};
struct D:public B, public C {
};
int main() {
return 0;
}
So this one while compiling gives us the following error:
\main.cpp:16:8: error: no unique final overrider for 'virtual void A::foo()' in 'D'
struct D:public B, public C {
If we would make the inheritance of B and C structs non-virtual, the code is compiling just right without any errors (but of course the error happens if we're calling dd.foo()). So what's the difference? Why do we have an error when we inherit our class virtually and no error if we do it straight?
Making
A
a virtual base class ofB
andC
ensures thatD
contains exactly oneA
subobject[1]. For this, bothB
andC
provide final overriders forfoo
[2] and both are inherited byD
[2], soD
has two final overriders forfoo
, making the program ill-formed[2].When
A
is not a virtual base class ofB
andC
,D
will contain two distinctA
subobjects[1]. Each of these subobjects will have their own inherited final overrider forfoo
[2].[1]: N4140 §10.1 [class.mi]/4:
[2]: §10.3 [class.virtual]/2 (emphasis mine):