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, virtual functions make sure that the right function is called for an object.
  • Runtime polymorphism is achieved by the virtual function.

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 object
parent *parentClassPointer; // make parent class pointer
child childClassObject; // make dreived class object
parentClassPointer = &childClassObject;// assign derived class object
// calling class fucntions
parentClassPointer->virtualDisplayMessage(); // Runtime polymorphism is acheieved using virtual function
parentClassPointer->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 child and inherit it with the parent class.
  • Line 19: We override the virtual function virtualDisplayMessage.
  • Line 24: We implement a non-virtual function called simpleDisplayMessage.

Note: We don’t need the virtual keyword in the child class when we have a virtual function in the parent class that is being overridden in the child class. Functions are considered virtual functions in the child class.

New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources