Pure Virtual function :-
Generally a function is declared virtual inside a base class and we redefine it the derived classes. The function declared in the base class seldom performs any task.
The following program demonstrates how a pure virtual function is defined, declared and invoked from the object of a derived class through the pointer of the base class. In the example there are two classes employee and grade. The class employee is base class and the grade is derived class. The functions getdata ( ) and display ( ) are declared for both the classes. For the class employee the functions are defined with empty body or no code inside the function. The code is written for the grade class. The methods of the derived class are invoked by the pointer to the base class.
program:-
#include<conio.h>
class employee {
int code
char name [20] ;
public:
virtual void getdata ( ) ;
virtual void display ( ) ;
};
class grade:
public employee
{
char grd [90] ;
float salary ;
public :
void getdata ( ) ;
void display ( );
};
void employee :: getdata ( )
{
}
void employee:: display ( )
{
}
void grade : : getdata ( )
{
cout<< “ enter employee’s grade “; cin> > grd ;
cout<< “\n enter the salary “ ; cin>> salary;
}
void grade : : display ( )
{
cout«" Grade salary \n"; cout« grd« " "« salary« endl;
}
void main ( )
{
employee *ptr ;
grade obj ;
ptr = &obj ;
ptr->getdata ( ) ;
ptr->display ( ) ;
getch ( ) ;
}
OUTPUT: -
enter employee’s grade A enter the salary 250000 Grade salary
A 250000