Coders Packet

Polymorphism in C++ using Virtual function

By Anuja Barje

The project uses the Polymorphism feature of C++ and virtual function to calculate the factorial of a number.

In this project, I have implemented the Polymorphism feature of C++ using a virtual function. Polymorphism means having "many forms" and it typically occurs when there is a hierarchy of classes and they are related by inheritance.
In the following program, we calculate the factorial of a number using
1. for loop
2. while loop
3. do-while loop
When we run the code, a call to the member function will cause a different function to be executed depending on the type of object that invokes the function. Now when you run the code without the 'virtual' keyword ie

code without virtual keyword

If we don't write the virtual keyword before int fact(), we get a wrong output as this

output without virtual keyword

The reason for the incorrect output is that call of the function fact() is being set once by the compiler as the version defined in the Factorial class. This is called static resolution of the function call. By making slight modifications, we can avoid this incorrect output. It is done by adding the keyword 'virtual' before int fact() like this

code with virtual keyword

A virtual function is a function in the Factorial class ie declared using virtual keyword. By doing so, this time the compiler looks at the content of the pointer instead of its type and we get the correct output.

output with virtual keyword

This is how the polymorphism feature is used. We have different classes with a function of the same name, same parameters but different implementations and by defining a function virtual, it signals to the compiler that we don't want static linkage for this particular function.
Thank you for reading!!!!!

Download Complete Code

Comments

No comments yet