What is virtual function?

Asked 07-Dec-2019
Viewed 558 times

1 Answer


Virtual Function in C++ 

The Virtual-Function is a function in base class, which is overrided in the derived class, and which tells the compiler to perform Late Binding on this function.

The VirtualKeyword is impliment(used) to make the member-function of the base class Virtual.

Wher the VirtualFunction is a member function in the base class that we expect to redefine in derived classes.

Mainly, the VirtualFunction is applied(used) in the base class in order to ensure that the function is overridden.

Its especially applies to cases where a pointer of base class points to an object of a derived class.

Property of Virtual Function in C++

  • The virtual-function is a member function in the base class that you redefine in a derived class. That is declared using the virtual keyword.
  • This is used to tell the compiler to perform dynamic linkage or late binding on the function. 
  • These are the necessity to use the single pointer to refer to all the objects of the different classes. This way, You may create the pointer to the base class that refers to all the derived objects. However, where the base class pointer contains the address of the derived class object, and its always executes the base class function. These type of issues can only be fixed by using the 'virtual' function. 
  • Where the 'virtual' is a keyword preceding the normal declaration of a function. 
  • Whenever the function is made virtual, C++ determines which function is to be invoked at the runtime based on the type of the object pointed by the base class pointer.

Late binding or Dynamic linkage

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

  • The Virtual functions must be members of some class.
  • The Virtual functions cannot be static members.
  • Those are accessed through object pointers.
  • Those can be a friend of another class.
  • The virtual function must be defined in the base class, even though it is not used.
  • These are the prototypes of a virtual function of the base class and all the derived classes must be identical. Whenever the two functions with the same name but different prototypes, C++ will consider them as the overloaded functions.
  • You cannot have a virtual constructor, but we can have a virtual destructor
  • Those are consider the situation when we don't use the virtual keyword.
class Base { 
    void print() {
        // code

class Derived : public Base {
    void print() {
        // code