27

Why do I sometimes see in C++ examples when talking about subclassing / inheritance, the base class has virtual keyword and sometimes the overridden function has also the virtual keyword, why it's necessary to add to the subclass the virtual key word sometimes? For example:

class Base 
{
  Base(){};
  virtual void f()
     ......
  }
};

class Sub : public Base
{
  Sub(){};
  virtual void f()
     ...new impl of f() ...
  }
};
Nayuki
  • 17,911
  • 6
  • 53
  • 80
user63898
  • 29,839
  • 85
  • 272
  • 514
  • 3
    Kinda duplicate of http://stackoverflow.com/questions/4024476/should-methods-that-implement-pure-virtual-methods-of-an-interface-class-be-decla/ if I have understood correct. – Kiril Kirov Mar 15 '11 at 09:02
  • 1
    Possible duplicate of [C++ "virtual" keyword for functions in derived classes. Is it necessary?](https://stackoverflow.com/questions/4895294/c-virtual-keyword-for-functions-in-derived-classes-is-it-necessary) – Satrapes May 25 '17 at 12:37
  • The link Satrapes provides will be a better source for this question. – NeoZoom.lua Jun 04 '18 at 05:46

1 Answers1

35

It is not necessary, but it helps readability if you only see the derived class definition.

§10.3 [class.virtual]/3

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 and same parameter list as Base::vf is declared, then Derived::vf is also virtual (whether or not it is so declared) and it overrides 97) Base::vf.

Where footnote 97) basically states that if the argument list differs, the function will not override nor be necessarily virtual

David Rodríguez - dribeas
  • 204,818
  • 23
  • 294
  • 489