Goseeko blog

What is a Virtual function in C++?

by Bhumika

A virtual function (VF) is a member function defined in a base class that is redefined (overridden) by a derived class. When you refer to a derived class object using a pointer or a reference to the base class, you can call a virtual function for that object and have it execute the derived class’s version of the function.

A virtual function in C++ is a base class member function that can modify in a derived class to enable polymorphism. To declare the function in the base class, use the virtual keyword. You can use a pointer or reference to call the virtual class and run its virtual version in the derived class after declaring the function in the base class. As a result, it asks the compiler to detect the object’s type and build a function bind at runtime (late binding or dynamic linkage).

Rules of Virtual Functions 

  • Static virtual functions are not possible.
  • A friend function of another class can be a virtual function.
  • To accomplish runtime polymorphism, virtual functions should be accessed using a pointer or reference of base class type.
  • Virtual functions should have the same prototype in both the base and derived classes.
  • They’re always defined in the base class and then overridden by derived classes. The derived class does not have to override (or redefine) the virtual function; in this instance, the base class version of the function use.
  • A virtual destructor is allow, while a VF is not.

Example 

#include <iostream>    

{    

 public:    

 virtual void display()    

 {    

  cout << “Base class is activated”<<endl;    

 }    

};    

class B:public A    

{    

 public:    

 void display()    

 {    

  cout << “Derived Class is activate”<<endl;    

 }    

};    

int main()    

{    

 A* a; //pointer of base class    

 B b; //object of derived class    

 a = &b;    

 a->display(); //Late Binding occurs    

}    

Output 

Derived Class is activate

Interested in learning about similar topics? Here are a few hand-picked blogs for you!

You may also like