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

Why Virtual Functions are Used?

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

Program without Virtual Function

Output

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

Output

virtual function example

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

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

Leave a Reply

Close Menu