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
Aa virtual base class ofBandCensures thatDcontains exactly oneAsubobject[1]. For this, bothBandCprovide final overriders forfoo[2] and both are inherited byD[2], soDhas two final overriders forfoo, making the program ill-formed[2].When
Ais not a virtual base class ofBandC,Dwill contain two distinctAsubobjects[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):