Override two methods at once

430 views Asked by At

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 { } 
};
2

There are 2 answers

1
Mike Seymour On BEST ANSWER

Yes. The standard says, in C++11 10.3/2

If a virtual member function vf is declared in a class Base and in a class Derived, derived directly or indirectly from Base, a member function vf with the same name [etc.] as Base::vf is declared, then [...] it overrides Base::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.

0
John S. V. On

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