Create a base class called Shape with two data members of double type
which could be used to compute the area of figures. Derive two specific
classes called Triangle and Rectangle from the base class Shape. Add to the
base class, a member function called Get Data to initialize base class data
members and another member function display Area to compute and display
the area of figures. Make display Area a virtual function and redefine this
function in the derived classes to suit their requirements. Using these three
classes design a program which will accept dimensions of a triangle or
rectangle interactively and display the area.
#include <iostream>
using namespace std;
class Shape
{
protected:
//has two double type values.
double height,base;
public:
//constructor to assign initial values to height and base
Shape(){
this->height=0;
this->base=0;
}
void GetData(){
cout<<"Enter height: ";
cin>>height;
cout<<"Enter base: ";
cin>>base;
}
double geHeight(){
return height;
}
double geBase(){
return base;
}
virtual void Area(){}
};
//class triangle inheriting class Shape
class Triangle : public Shape
{
public:
void Area()
{
cout<<"Height: "<<height<<"\n";
cout<<"Base: "<<base<<"\n";
cout<<"Area of Triangle = "<<(height*base)/2;
}
};
//class Rectangle inheriting class Shape
class Rectangle : public Shape
{
public:
void Area()
{
cout<<"Side a: "<<height<<"\n";
cout<<"Side b: "<<base<<"\n";
cout<<"Area of Rectangle = "<<(height*base);
}
};
void main(){
Shape *shape;
Triangle triangle;
triangle.GetData();
shape=▵
shape->Area();
Rectangle rectangle;
cout<<"\n\n";
rectangle.GetData();
shape=&rectangle;
shape->Area();
cout<<"\n\n";
system("pause");
}
Comments
Leave a comment