C++ program to illestrate virtual functions

AIM
A program to access the member of the derived class objects through an array of members. In this program, both the base class and the derived class member functions are preceded by the keyword

ALGORITHM

1. Start the process
2. Invoke the class with pointer
3. Assign ptr[0] <- &objb; i. Assign ptr[1] <- &objc; 4. Ptr(0)points the getdata() a. Get the values of x and y 5. Ptr(1) points to the getdata() a. Get the roll no and name of the student 6. Ptr(0) and ptr(1) are points to the display() a. Print the values 7. Stop the process PROGRAM

#include<iostream.h>
#include<conio.h>
 
class base
{
private: int x;
float y;
public:  
virtual void getdata( );
virtual void display( );
};
class devb: public base
{
private: int roll;
char name[20];
public:  virtual void getdata( );
virtual void display( );
};
class devc : public  base
{
private: float height;
float weight;
public : virtual void getdata( );
virtual void display( );
}:
void base :: getdata( )
{
cout<<” Enter any Integer”;
cin>>x;
cout<<”Enter a real no”;
cin>>y;
}
void base ::display( )
{
cout<<”The no X=<<x<<”Y=<<y<<endl;
}
void devb :: display( )
{
cout<<”Roll of the Student is:<<roll<<endl;
cout<<” Name of the Student is:<<name<<endl;
}
void devb :: getdata( )
{
cout<<”Enter the Roll of  the Student:;
cin>>roll;
cout<<”Enter Name of Student :;
cin>>name;
}
void devc :: getdata( )
{
cout<<”Enter height and weight”;
cin>>height>>weight;
}
void devc :: display( )
{
cout<<”Height :<<height<<endl;
cout<<”Weight :<<weight<<endl;
}
void main( )
{
base *ptr[3];
devb objb;
devc objc;
clrscr( );
ptr[0] = &objb;
ptr[1] = &objc;
ptr[0] ->getdata( );
ptr[1] -> getdata( );
ptr[1] -> display( );
ptr[1] -> display( );
getch ( );
}

OUTPUT

Enter the Roll of the Student: 101
Enter Name of Student : salah
height and weight 170 72

Roll of the Student is:101
Name of the Student is:salah
Height :170
Weight :72

Editorial Team
Editorial Team

We are a group of young techies trying to provide the best study material for all Electronic and Computer science students. We are publishing Microcontroller projects, Basic Electronics, Digital Electronics, Computer projects and also c/c++, java programs.

Leave a Reply

Your email address will not be published. Required fields are marked *

Get the latest updates on your inbox

Be the first to receive the latest updates from Codesdoc by signing up to our email subscription.

    StudentProjects.in