Virtual function in C++ is a member function in the base class that we redefined in a derived class. With the use of a virtual function, we ensure that the function is overridden.
A virtual function lets the compiler know to perform dynamic linkage or late binding on the function (that is the called function needs to be resolved at run time).
A keyword ‘virtual‘ is used preceding with the function to be overridden. A virtual function cannot be a static member nor we can have a virtual constructor.
Let us understand through an example, we will first see a program without the use of virtual keywords and next with the use of virtual.
C++ Program Overriding a non-virtual function
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | // C++ program for function overriding without virtual function #include <iostream> using namespace std; class Animal { public: void display() { cout << "I am Animal" << endl; } }; class Dog: public Animal { public: void display() { cout << "I am a Dog" << endl; } }; int main(void) { Animal *a; Dog d; a = &d; a->display(); return 0; } |
Output:
1 | I am Animal |
As you can see in the above program that we created a pointer object for the base class and the function is the same in both of the classes which are to be overridden. But even though the object of the base class points to the derived class (a = &d;
), when we call it through an object a
, we still get the display() function of the base class.
Therefore, here we need a virtual function in order to get access to the member of the derived class which we will see in the program below.
C++ Program Overriding using a virtual function
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | // C++ program for function overriding with virtual function #include <iostream> using namespace std; class Animal { public: virtual void display() //virtual function { cout << "I am Animal" << endl; } }; class Dog: public Animal { public: void display() { cout << "I am a Dog" << endl; } }; int main(void) { Animal *a; Dog d; a = &d; a->display(); return 0; } |
Output:
1 | I am a Dog |
As you can see above is the same first program but with a virtual display()
function. And now the result is different, the base object a
which is pointed to the derived class gives the display() function of the derived class indicating the virtual function of the base class is overridden by the derived class.