Virtual Function Example in C++
A virtual function is a member function which is declared within a base class and is re-defined(Overriden) by a derived class. When you refer to a derived class object using a pointer or a reference to the base class, you can call a virtual function for that object and execute the derived class’s version of the function.
- Virtual functions ensure that the correct function is called for an object, regardless of the type of reference (or pointer) used for function call.
- They are mainly used to achieve Runtime polymorphism
- Functions are declared with a virtual keyword in base class.
- The resolving of function call is done at Run-time.
The program demonstrates the concept of virtual functions in C++.
- We define a base class Parent with a virtual function display(). Then we define a derived class Child which overrides the display() function of the parent class.
- In the main() function, we create an object o of type Parent but assign it a memory location of the Child class. This is possible because the Child class is a derived class of Parent.
- When we call the display() function using the pointer o, it calls the display() function of the Child class because we have marked the function as virtual in the base class. This is known as dynamic polymorphism or late binding.
Source Code
#include<iostream>
using namespace std;
class Parent
{
public:
virtual void display()
{
cout<<"Display Parent"<<endl;
}
};
class Child:public Parent
{
public :
void display()
{
cout<<"Display Child"<<endl;
}
};
int main()
{
Parent *o =new Child();
o->display();
return 0;
}
To download raw file
Click Here
Output
Display Child