Summary: In this tutorial, we will learn about the virtual function and overriding of functions in C++.

Introduction

Function overriding is defined as the redefining of the base class’s function in the derived class with the same function signature.

In C++, only the base class’s virtual function can be overridden in the derived class.

Virtual Function is a function that is declared as virtual in the function declaration.

Example:

Why Virtual Functions are Necesarry?

Consider the following C++ program without a virtual function.

Output

virtual function in C++

In the above program, the Derived class is inheriting the Base class.

In both Derived and Base class, we have declared display() function.

But in the main method, on invoking the display() function from the derived class’s pointer object created using the base class reference, the display() method of the base class gets invoked.

This is because display() function in derived class is not overriding the base class display() method.

To get rid of this problem we use virtual keyword.

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

C++ program with a virtual function.

Output

virtual function example

This time we have successfully overridden the Base class display() function using the virtual keyword.

Hence we can conclude that only those functions can be overridden in the 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