In C++ when we override the base class function in the derived class is known as Function Overriding. We first need to make the function virtual to successfully override it in the derived class.

So let’s first understand Virtual Function.

Virtual Function is a function which is declared virtual in the function declaration. E.g

Why Virtual Functions are Used?

To understand why we need a function to be declared as virtual in C++, take e.g

Program without Virtual Function


virtual function in C++

In the above program, inheritance is used. In both Derived and Base class, we have declared display() function. But in the main on using the base class reference to create Derived class pointer object and on calling display() function from the same pointer object i.e derived.display() , Base class display() function is getting invoked.

This is because display() function in Derived class is not overriding the Base class display() function.

To get rid of this problem we use virtual keyword.

Let’s see what happens when we declare Base class display() function as virtual.

Program with Virtual Function


virtual function example

We have successfully overridden Base class display() function using the virtual keyword.

Hence we conclude that only those functions can be overridden in Derived class which is declared virtual in the base class. As a result, virtual function helps in achieving runtime polymorphism also known as late binding.

Leave a Reply