What is a virtual function?

  • A virtual function is used to replace the implementation provided by the base class. The replacement is always called whenever the object in question is actually of the derived class, even if the object is accessed by a base pointer rather than a derived pointer.
  • A virtual function is a member function which is present in the base class and redefined by the derived class.
  • When we use the same function name in both base and derived class, the function in base class is declared with a keyword virtual.
  • When the function is made virtual, then C++ determines at run-time which function is to be called based on the type of the object pointed by the base class pointer. Thus, by making the base class pointer to point different objects, we can execute different versions of the virtual functions.

Rules of a virtual function:

  • The virtual functions should be a member of some class.
  • The virtual function cannot be a static member.
  • Virtual functions are called by using the object pointer.
  • It can be a friend of another class.
  • C++ does not contain virtual constructors but can have a virtual destructor.