Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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() ...   } }; 
like image 449
user63898 Avatar asked Mar 15 '11 08:03

user63898


People also ask

Can we use override without virtual keyword?

You cannot override a non-virtual or static method. The overridden base method must be virtual , abstract , or override . An override declaration cannot change the accessibility of the virtual method. Both the override method and the virtual method must have the same access level modifier.

Does a function have to be virtual to be overridden?

Because virtual functions are called only for objects of class types, you cannot declare global or static functions as virtual . The virtual keyword can be used when declaring overriding functions in a derived class, but it is unnecessary; overrides of virtual functions are always virtual.

What happens if you don't override virtual function?

If you don't override a pure virtual function in a derived class, that derived class becomes abstract: class D2 : public Base {

Why do we use virtual keyword?

A virtual keyword is used to specify the virtual method in the base class and the method with the same signature that needs to be overridden in the derived class is preceded by override keyword.


1 Answers

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

like image 198
David Rodríguez - dribeas Avatar answered Sep 19 '22 21:09

David Rodríguez - dribeas