Explain Virtual Functions and Runtime Polymorphism in C++

bookmark

Any function when accompanying the virtual keyword exhibits the behavior of a virtual function. Unlike normal functions that are called in accordance with the type of pointer or reference used, virtual functions are called as per the type of the object pointed or referred.

In simple terms, virtual functions resolve at runtime, not anytime sooner. Use of virtual functions could also be understood as writing a C++ program leveraging the concept of runtime polymorphism. Things essential to writing a virtual function in C++ are:

  • A base class
  • A derived class
  • A function with the same name in both the classes i.e. the base class and the derived class
  • A pointer or reference of base class type that points or refers, respectively to an object of the derived class