virtual
functions make sure that the right function is called for an object.virtual
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;}
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.