Virtual functions are functions in a parent class that are meant to be overwritten in the children classes.
Output:
The difference can be spotted when pointers are used. Virtual functions have late binding. Non virtual functions have early binding.
This can be understood by an example:
Output:
Couple of things to spot:
square_1
with type Square
and square_2
with type Figure
.getPerimeter
function is declared as virtual. This means that the code the
child class (Square
) executes for both pointers.getArea
function is non-virtual function.
So for the pointer square_2
the code
from the parent class (Figure
) will be executed.