Implementation of Virtual and Pure Virtual Function in C++

#include <iostream.h>
#include <conio.h>
 
class  base
{
private:
    int x;
    float y;
 
public :
    virtual void getdata( );
    virtual void display( )=0;
};
 
class derived : public base
{
private:
    int roll,m[10],sum,n,no;
    char name[20];
    float avg;
public :
    void getdata( );
    void  display( );
};
 
void base :: getdata( )
{
 
}
void base :: display( )
{
}
void derived :: getdata( )
{
    cout<<"\n\nEnter Roll of the Student: ";
    cin>> roll;
 
    cout<<" \nEnter Name of the Student: ";
    cin>>name;
 
    sum=0;
 
    cout<<"\nEnter Number of Subjects : ";
    cin>>n;
 
    for(int i=0; i<n; i++)
    {
        cout<<"\nEnter Marks in Subject "<<i+1<<": ";
        cin>>m[i];
        sum+=m[i];
    }
    avg=sum/n;
}
 
void derived :: display( )
{
 
    cout<<"\n\n\n";
 
    cout<<"\nRoll No :"<<roll <<endl;
 
    cout<<"\nName    :"<<name<<endl;
 
    cout<<"\nAverage :"<<avg<<endl;
 
}
 
int main( )
{
    //clrscr();
    cout<<"\n\n **** IMPLEMENTATION OF VIRTUAL AND PURE VIRTUAL FUNCTOIN ****\n";
    int no;
    base * ptr;
    derived obj;
    ptr = &obj;
    cout<<"\n\n Enter Number of Records :";
    cin>>no;
    for(int i=0; i<no; i++)
    {
 
        cout<<"\n\n\n\n Details of Student "<<i+1<<" :- "<<endl;
 
        cout<<"\n\n\t******* READING DATA ******* \n";
 
        ptr -> getdata( );
 
        cout<<"\n\n\t******* DISPLAYING DATA ******* ";
 
        ptr -> display( );
 
    }
 
    getch();
 
}

 OUTPUT


**** IMPLEMENTATION OF VIRTUAL AND PURE VIRTUAL FUNCTOIN ****


Enter Number of Records :2


Details of Student 1 :-


******* READING DATA *******


Enter Roll of the Student: 01

Enter Name of the Student: AAA

Enter Number of Subjects : 2

Enter Marks in Subject 1: 45

Enter Marks in Subject 2: 78


******* DISPLAYING DATA *******

Roll No :1

Name :AAA

Average :61


Details of Student 2 :-


******* READING DATA *******


Enter Roll of the Student: 02

Enter Name of the Student: BBB

Enter Number of Subjects : 2

Enter Marks in Subject 1: 54

Enter Marks in Subject 2: 67


******* DISPLAYING DATA *******

Roll No :2

Name :BBB

Average :60

Leave a Reply

Your email address will not be published.