Virtual Function in C++ with Example Program

Virtual Function in C++:

When we use the same function name in both the base and derived classes, the function in the base class is called a Virtual Function. When a function is made virtual keyword then it determines which function to use at run-time based on the type of the object pointed to by the base pointer, rather than the type of the pointer. Thus, by making the base pointer point to different objects, we can execute different versions of the virtual function.

Program:

#include<iostream.h>
#include<conio.h>
using namespace std;
class base
{
public:
void display()
{
cout<<"\n Display base";
}
virtual void show()
{
cout<<"\n Show base";
};
class derived: public base
{
public:
void display()
{
cout<<"\n Display derived";
}
void show()
{
cout<<"\n Show derived";
}
};
int main()
{
base b;
derived d;
base *ptr;
cout<<"\n ptr points to base\n"; ptr=&b; ptr->display();
ptr->show();
cout<<"\n\n ptr points to derived\n"; ptr=&d; ptr->display();
ptr->show();
return 0;
}

Output:
ptr points to base

Display base
Show base

ptr points to derived

Display base
Show derived