I saw code in a derived class recently in which the programmer put virtual
in front of the functions overridden. Is this common? I thought it was very odd and it kind of caught me off guard.
Edit: I'm not asking what virtual does, I'm asking why someone would put virtual in a derived class that is already overriding virtual functions in its base class.
EX:
class B { public: virtual void foo(); .... }; class D : public B { public: virtual void foo(); // could have just put void foo(); ... };
To use the redefined virtual verson of a function in a derived class (take advantage of polymorphism see), you must call the function via a pointer or reference to an instance of the derived class. Otherwise the static type of the object will be used.
It is not mandatory for the derived class to override (or re-define the virtual function), in that case, the base class version of the function is used. A class may have virtual destructor but it cannot have a virtual constructor.
Of course you can do it. Virtual method is optional to override so it doesn't matter that you declare it in class A or B.
If the derived class does not define the pure virtual function; it will not throw any error but the derived class becomes an abstract class. All the derived classes may or may not redefine the virtual function. All the derived classes must define the pure virtual function.
virtual
is needed for overrideable functions at the highest (least derived) level. It is optional, but harmless at lower (more derived) levels. It's good for self-documenting the code.
It is very common. Many style guides recommend it, e.g. Google. The purpose is to enhance readability of the code.
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