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() ... } };
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.
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.
If you don't override a pure virtual function in a derived class, that derived class becomes abstract: class D2 : public Base {
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With