In C++, the virtual
keyword is used to create a 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.
virtual
functions make sure that the right function is called for an object.virtual
function.virtual returntype functionName(/*No of parameters*/)
{
// body of function
}
#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;}
parent
.virtualDisplayMessage
.simpleDisplayMessage
.child
and inherit it with the parent
class.virtualDisplayMessage
.simpleDisplayMessage
.Note: We don’t need the
virtual
keyword in thechild
class when we have avirtual
function in theparent
class that is being overridden in thechild
class. Functions are consideredvirtual
functions in thechild
class.