in c++ when subclassing why sometimes need to add virtual keyword to overridden function?
Asked Answered
H

1

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() ...
  }
};
Hipped answered 15/3, 2011 at 8:55 Comment(3)
Kinda duplicate of #4024976 if I have understood correct.Vitiligo
Possible duplicate of C++ "virtual" keyword for functions in derived classes. Is it necessary?Heroic
The link Satrapes provides will be a better source for this question.Entoil
R
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

Rath answered 15/3, 2011 at 8:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.