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.
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.
The sample code will output the following
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.
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.
Inside the int main(), we are applying pointers here along with creating the class objects base_object, output_one_object and output_two_object.
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.
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.