Breaking down Virtual functions and polymorphism

Virtual functions and polymorphism are the most complicated concept in C++ object orientated programming. The best way to define a virtual function is that a virtual function is a function that is declared virtual in a base class and overridden in a derived class.

An example of declaring a virtual function is:
virtual void virtual_base();

Once the virtual function has been defined in a class, it will need to be redefined in other class declarations expect without the “virtual” keyword.

virtual function graph

The code sample below puts this visual diagram into practice by defining three classes named Base, Output_one and Output_two. The classes Output_one and Output_two apply the concept of inheritance to set up the declaration of the virtual function declared in the Base class.

virtual functions code 1

virtual functions code 2

virtual functions code 3

The sample code will output the following

output of virtual function code

Let’s run through what is going on here. Firstly we are defining three classes. In the Base class we are defining our virtual function. This means that we can redefine it in a derived class which is exactly what happens in the Output_one and Output_two class. The Base class has been inherited and the virtual function has been redefined without the “virtual” keyword.

breakdown 1

The function members inside the classes are then implemented with output text in each one, showcasing outputting the declared virtual function and derived virtual functions.

breakdown 2

Inside the int main(), we are applying pointers here along with creating the class objects base_object, output_one_object and output_two_object.

breakdown 3

Since virtual_base() is declared as a virutal function, the complier will determine which version of virutal_base() to execute based on the pointer “p”. In the first case, p points to an object of the Base class, so the version of virtual_base() is executed in the program.

The next step shows the pointer p is assigned to the address of Output_one_object. The complier will then check again what type of object the pointer p is pointing to and determines what version of virutal_base() to execute. The same step happens when the pointer p is assigned to the address of Output_two_object, the version of virtual_base() will be executed inside the Output_two_object class.

pointers and virtual functionsbreakdown 4

Remember when a virtual function is called through a base class pointer, the version of the virtual function actually executed is determined by the complier and the type of object being pointed to.

Share this post