Virtual Functions in C++

Virtual Functions in C++

If function overriding takes place in inheritance then we might need to use virtual functions as well. Virtual functions are the member functions defined in the parent class and overridden in the child class. They are used while late binding comes into play.

If we don’t define the member functions of parent class as virtual then unexpected results will be produced. For instance, consider the code in the following example.

Virtual Functions in C++

We can see that the pointer of Person class holds the address of an object of the Student class at line 29 but the Person class pointer will call the function of Person class at line 30 instead of overridden function defined in the Student class due to the early binding. As a result the output of the above code is as below.

person

Virtual Keyword

If we use the ‘virtual’ keyword with the member function defined in the parent class then it will allow late binding at runtime and then the Person class pointer will call the overridden function of Student class instead of the member function defined in the Person class due to late binding as shown in the code given below.

Virtual Keyword

We can see at line 9 that keyword ‘virtual’ is used before the member function to allow late binding. The rest of the code is same. The output of the above code is as below.

student

Another use of Virtual Functions

Another interesting use of virtual functions is that it allows to access the private members of child class through the pointer object of the parent class due to the reason that compiler restricts the access of private member at the time of compilation but these restrictions are ignored at the time of execution in late binding as shown in the example given below.

Another use of Virtual Functions

We can see at line 16 that member function is declared as private which means that it cannot be accessed outside the class due to private access modifier being used with it. But at line 27 this member function is called by the pointer object of it parent class. The parent class also has its own version of display function which is declared virtual thus allows late binding. So when the pointer object of parent class calls the function ‘display’ at line 27, it calls the member function defined in the child class and produces the output as below.

display

More Related Articles For You

    C++ Tutorial

    C++ Quizzes

 

Search

Shortcodes Ultimate

 
Follow Us
 
BGP