Ticker

6/recent/ticker-posts

Pure Virtual Functions in C++ Programming

Pure Virtual Functions 

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.

#include 

#include 

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 ( ) ; getche ( ) ; } 

Output 

enter employee’s grade A 

enter the salary 250000 

Grade salary 

A     250000

ALSO SEARCH:

"pure virtual functions in C++ programming examples"

"pure virtual functions in C++ programming language"

"pure virtual function in c++ program"

"pure virtual function in C++"

"pure virtual function in C++ use"

"pure virtual function in C++ example"