Image

C++ - Virtual Function - Virtual Function

Virtual Function

A virtual function is a member function that is declared within a base class and redefined by a derived class. To create virtual function, precede the function’s declaration in the base class with the keyword virtual. When a class containing virtual function is inherited, the derived class redefines the virtual function to suit its own needs.

#include<conio.h>
#include<iostream.h>
class Base1{
 public:
	virtual void show(){
	 cout<<"\nThis is Base 1 class";
	}
};
class Base2:public Base1{
 public:
	void show(){
	 cout<<"\nThis is Base 2 class";
	}
};
class Base3:public Base1{
 public:
	void show(){
	 cout<<"\nThis is Base 3 class";
	}
};
void main(){
clrscr();
Base1 *b1;
Base2 b2;
Base3 b3;
b1=&b2;
b1->show();
b1=&b3;
b1->show();
getch();
}