C++ Virtual Function
A virtual function is such function which is declared inside the base class and redefined by the derive class. C++ uses a virtual keyword to make a function as a virtual function. The virtual function is always defined in the base class. The concept of polymorphism is also achieved using the virtual function. If two functions with the same name present in base and derive class then the pointer of the base class would call the functions associated only with the base class.
C++ Virtual Function Example
#include <iostream>
using namespace std;
class Base
{
public:
virtual void show()
{
cout<<"\n Showing base class....";
}
void display()
{
cout<<"\n Displaying base class...." ;
}
};
class Derive:public Base
{
public:
void display()
{
cout<<"\n Displaying derive class....";
}
void show()
{
cout<<"\n Showing derive class....";
}
};
int main()
{
Base B;
Base *ptr;
cout<<" Pointer points to base:\n" ;
ptr=&B;
ptr->display();
ptr->show();
cout<<"\n\n Pointer points to drive:\n";
Derive D;
ptr=&D;
ptr->display();
ptr->show();
}
Pointer points to base: Displaying base class.... Showing base class..... Pointer points to derive: Displaying base class..... Showing derive class.....