Create a base class shape. Use this class to store two double type values that could be used to compute the area of figures. Derive two specific classes called triangle and rectangle from the base shape. Add to the base class, a member functionget_data() to initialize the base class data members and another member function display_area() to compute and display the area of figures. Make display_area() as a virtual function and redefine this function in the derived class to suit their requirements.
CODING:
#include<iostream.h>
#include<conio.h>
class shape
{
protected:
double height;
double width;
public:
void get_data()
{
cout<<"\nEnter the Height:";
cin>>height;
cout<<"Enter the Width:";
cin>>width;
}
double virtual disp_area()=0;
};
class rectangle:public shape
{
public:
double disp_area()
{
cout<<"\nHeight:"<<height<<"\nWidth:"<<width;
return height*width;
}
};
class triangle:public shape
{
public:
double disp_area()
{
cout<<"\nHeight:"<<height<<"\nWidth:"<<width;
return 0.5*height*width;
}
};
void main()
{
clrscr();
shape *s;
rectangle r1;
s=&r1;
cout<<"RECTANGLE:";
r1.get_data();
cout<<"\nArea of Rectangle:"<<s->disp_area();
triangle t1;
cout<<"\nTRIANGLE:";
t1.get_data();
s=&t1;
cout<<"\nArea of Triangle:"<<s->disp_area();
getch();
}
CODING:
#include<iostream.h>
#include<conio.h>
class shape
{
protected:
double height;
double width;
public:
void get_data()
{
cout<<"\nEnter the Height:";
cin>>height;
cout<<"Enter the Width:";
cin>>width;
}
double virtual disp_area()=0;
};
class rectangle:public shape
{
public:
double disp_area()
{
cout<<"\nHeight:"<<height<<"\nWidth:"<<width;
return height*width;
}
};
class triangle:public shape
{
public:
double disp_area()
{
cout<<"\nHeight:"<<height<<"\nWidth:"<<width;
return 0.5*height*width;
}
};
void main()
{
clrscr();
shape *s;
rectangle r1;
s=&r1;
cout<<"RECTANGLE:";
r1.get_data();
cout<<"\nArea of Rectangle:"<<s->disp_area();
triangle t1;
cout<<"\nTRIANGLE:";
t1.get_data();
s=&t1;
cout<<"\nArea of Triangle:"<<s->disp_area();
getch();
}
Comments
Post a Comment