Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override two methods at once

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 { } 
};
like image 536
MaksymB Avatar asked Dec 26 '22 02:12

MaksymB


2 Answers

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.

like image 93
Mike Seymour Avatar answered Dec 27 '22 16:12

Mike Seymour


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

like image 20
John S. V. Avatar answered Dec 27 '22 15:12

John S. V.