The code below surprisingly compiles in VS 2012.
Method C::f() overrides methods in both base classes.
Is this standard behavior? I looked into C++11 standard, and didn't find any explicit mentioning of such situation.
class A { virtual void f() = 0; };
class B { virtual void f() = 0; };
class C : public A, public B {
virtual void f() override { }
};
Yes. The standard says, in C++11 10.3/2
If a virtual member function
vf
is declared in a classBase
and in a classDerived
, derived directly or indirectly from Base, a member functionvf
with the same name [etc.] asBase::vf
is declared, then [...] it overridesBase::vf
.
There are no special cases for multiple base classes, so a function declared in the derived class will override a suitable function in all base classes.
Herb Sutter explains how to deal with this here.
According to the article:
class B1 {
public:
virtual int ReadBuf( const char* );
// ...
};
class B2 {
public:
virtual int ReadBuf( const char* );
// ...
};
class D : public B1, public B2 {
public:
int ReadBuf( const char* ); // overrides both B1::ReadBuf and B2::ReadBuf
};
This overrides BOTH functions with the same implementation
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With