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 GetData to initialize base class data
members and another member function displayArea to compute and display
the area of figures. Make displayArea 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
{
public:
double first,second;
void getData ()
{
cin>>first>>second;
}
virtual void displayArea () = 0;
};
class Triangle:public Shape
{
public: void displayArea ()
{
cout<<"The area of Triangle: "<<0.5*first*second<<endl;
}
};
class Rectangle:public Shape
{
public:
void displayArea ()
{
cout<<"The area of the Rectangle: "<<first*second<<endl;
}
};
int main()
{
Triangle triangle;
Shape *shape_triangle = ▵
cout<<"Enter base and height: ";
shape_triangle->getData();
shape_triangle->displayArea();
Rectangle rec;
Shape *shape_rect = &rec;
cout<<"Enter length and width: ";
shape_rect->getData();
shape_rect->displayArea();
return 0;
}
Comments
Leave a comment