What does the virtual keyword do?
Virtual keyword
In C++, the virtual keyword is used to create a virtual function.
Virtual function
A virtual function is the member function of the class. This function is declared in the parent class and overridden by the child class.
This is true when a pointer from a parent class points to a child class object.
Importance of a virtual function
- Irrespective of the nature of the reference (or the pointer) that is used for a function call,
virtualfunctions make sure that the right function is called for an object. - Runtime polymorphism is achieved by the
virtualfunction.
Syntax
virtual returntype functionName(/*No of parameters*/)
{
// body of function
}
Code example
#include<iostream>using namespace std;class parent {public:virtual void virtualDisplayMessage(){cout << "Parnent class function virtual function."<<endl;}void simpleDisplayMessage(){cout << "Parent class simple function."<<endl;}};class child : public parent {public:void virtualDisplayMessage(){cout << "Child class override virtual function. "<<endl;}void simpleDisplayMessage(){cout << "Child class simple function. "<<endl;}};int main(){// declare class objectparent *parentClassPointer; // make parent class pointerchild childClassObject; // make dreived class objectparentClassPointer = &childClassObject;// assign derived class object// calling class fucntionsparentClassPointer->virtualDisplayMessage(); // Runtime polymorphism is acheieved using virtual functionparentClassPointer->simpleDisplayMessage(); // Non virtual function,return 0;}
Code explanation
- Line 4: We create the class name
parent. - Line 6: We implement a public virtual function called
virtualDisplayMessage. - Line 11: We implement a non-virtual function called
simpleDisplayMessage. - Line 17: We create the class name
childand inherit it with theparentclass. - Line 19: We override the virtual function
virtualDisplayMessage. - Line 24: We implement a non-virtual function called
simpleDisplayMessage.
Note: We don’t need the
virtualkeyword in thechildclass when we have avirtualfunction in theparentclass that is being overridden in thechildclass. Functions are consideredvirtualfunctions in thechildclass.