A virtual function is the member function of the base class that is declared within the body of the base class. It is redefined (overridden) with the help of the derived class. When we call the object of a derived class using the pointer or reference to the base class, we call the derived class virtual function for that object.
We use virtual functions to ensure that the correct function is called for an object, regardless of the reference type used to call the function. They are basically used to achieve the runtime polymorphism and are declared in the base class by using the virtual
keyword before the function.
Here are some of the rules of using the virtual function:
We cannot declare virtual functions as static.
The prototype of the virtual function must be the same in the parent class and the derived class.
We can access the virtual functions with the help of pointers. We could also do it by using the reference of the base class to achieve the run-time polymorphism.
Virtual functions can be another class’s friend function.
We can or cannot override the virtual function of the base class with the help of the derived class.
A class cannot have a virtual constructor, but it can have a virtual destructor.
Here’s an example of how to use a virtual function:
#include <iostream>using namespace std;class A{public:virtual void raw(){cout << "Base Function" << endl;}};class B : public A{public:void raw(){cout << "Derived Function" << endl;}};int main(void){B obj;obj.raw();return 0;}
Lines 3–10: We make a base class called class A
, which has a virtual function raw
, and it prints something.
Lines 12–19: We make a derived class, class B
. This is inherited from class A
so that it can use the class A
function to override it.
Lines 21–26: We make the object of the class B
and call the raw
function of class B
.