Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using 'virtual' in derived class

Tags:

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();   ... }; 
like image 277
Person Avatar asked Feb 11 '10 03:02

Person


People also ask

What if virtual function is not defined in derived class?

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.

Is it mandatory to override virtual function in derived?

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.

Can we inherit virtual function in C++?

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.

What happens if a pure virtual function is not redefined in a derived class?

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.


2 Answers

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.

like image 61
James Curran Avatar answered Oct 05 '22 15:10

James Curran


It is very common. Many style guides recommend it, e.g. Google. The purpose is to enhance readability of the code.

like image 27
Ralph Avatar answered Oct 05 '22 16:10

Ralph