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
using namespace std;
virtual void show()
cout<<"\n Showing base class....";
cout<<"\n Displaying base class...." ;
class Derive:public Base
cout<<"\n Displaying derive class....";
cout<<"\n Showing derive class....";
cout<<" Pointer points to base:\n" ;
cout<<"\n\n Pointer points to drive:\n";
Pointer points to base:
Displaying base class....
Showing base class.....
Pointer points to derive:
Displaying base class.....
Showing derive class.....