Virtual Function in C++

A virtual function is a member function of the base class (parent) and a virtual function redefine in a derived class (child). A virtual function is declared by using the virtual keyword.

  • It is used to tell the compiler to perform dynamic linkage or late binding on the function.

Function overriding means to write a function in the child class that is already present in the parent class.

Function overriding means making a function more important than any other function.

In late binding function call is resolved during runtime. Therefore compiler determines the type of object at runtime and then binds the function call.

Example of C++ program without virtual function

without virtual function
without virtual function

Output

Value of n1 is : 33

Example of C++ program using virtual function

Late binding can be implemented by making a function as a virtual function.

C++ program to demonstrate working of virtual function

 

Features of Virtual Function

  • Virtual functions must be members of some class.

    Virtual functions must be members of some class
    Virtual functions must be members of some class
  • Virtual functions cannot be static members.

If we try to add virtual functions as static members, then the following error will display;

[Error] member ‘display’ cannot be declared both virtual and static

Virtual functions cannot be static members
Virtual functions cannot be static members
  • The compiler can access the Virtual Functions through object pointers.

compiler can access the Virtual Functions through object pointers
the compiler can access the Virtual Functions through object pointers
  • A virtual function must be defined in the base/parent class, whether it is used or not.

In this example, the display is a virtual function in base class A.

  • The signatures of a virtual function of the base class and all the derived classes must be the same.

The signatures of a virtual function of the base class and all the derived classes must be the same.
The signatures of a virtual function of the base class and all the derived classes must be the same.

Why it must be the same? If two functions with the same name exist but have different signatures, then the compiler will understand these functions as overloaded functions.

  • A virtual destructor is possible but a program cannot have a virtual constructor.

 

[Examples – Difference] Early binding and Late Binding in C++

Virtual Function MCQs