Explain Virtual Function in C++?

A virtual function is a member function in the base class that you redefine in a derived class. It is declared using the virtual keyword.

  • Used to message compiler to perform dynamic linkage or late binding on the function.
  • Must be members of some class.
  • Cannot be static members.
  • Accessed through object pointers.
  • Can be a friend of another class.
  • Must be defined in the base class, even though it is not used.
  • We cannot have a virtual constructor, but we can have a virtual destructor.

CODE:

#include <iostream>    
{    
 public:    
 virtual void display()    
 {    
  cout << "Base class is invoked"<<endl;    
 }    
};    
class B:public A    
{    
 public:    
 void display()    
 {    
  cout << "Derived Class is invoked"<<endl;    
 }    
};    
int main()    
{    
 A* a;    //pointer of base class    
 B b;     //object of derived class    
 a = &b;    
 a->display();   
}

Further, a “do-nothing” function is known as a pure virtual function. A pure virtual function is a function declared in the base class that has no definition relative to the base class.

virtual void display() = 0;