Virtual Function in CPP

A virtual function is a member function that is declared within the base class and redefined by a derived class. It is declared by the keyword virtual. 

You will understand more clearly after the example.

#include<iostream.h>
#include<conio.h>


class A
{				
public:
virtual void show()				
{				
cout << "A show called" << endl;				
}				
};		
class B:public A				
{			
public:			
void show()				
{				
cout << "B show called" << endl;				
}				
};			
void main()				
{			
A a1,*ptr;			
clrscr();			
ptr=&a1;		
ptr->show();			
B b1;			
ptr=&b1;			
ptr->show();			
getch();				
}

Output:
A show called
B show called

If you do not write virtual keyword in the base class then output will be
A show called
A show called

 

Leave a Reply