Create a class named ‘CalculateArea’ to calculate the area of three different diagrams i.e. Rectangle, Triangle and a Square using function overloading.
First prompt the user to select the diagram for which he wants the area:
Press 1 for Rectangle
Press 2 for Triangle
Press 3 for Square
After the selected option, call the respective function of the selected diagram and print the area.
Area of rectangle: length*width;
Area of triangle: ½(base*height);
Area of square: (length)2
#include <iostream>
using namespace std;
class CalculateArea
{
public:
virtual float Calculate() = 0;
virtual void Assign() = 0;
};
class Rectangl:public CalculateArea
{
float length;
float width;
public:
Rectangl(float _length=0, float _width=0)
:length(_length), width(_width){}
void Assign()
{
cout << "Please, enter a length: ";
cin >> length;
cout << "Please, enter a width: ";
cin >> width;
}
float Calculate()
{
return length*width;
}
};
class Triangle :public CalculateArea
{
float base;
float height;
public:
Triangle(float _base = 0, float _height = 0)
:base(_base), height(_height) {}
void Assign()
{
cout << "Please, enter a base: ";
cin >> base;
cout << "Please, enter a height: ";
cin >> height;
}
float Calculate()
{
return base*height*0.5;
}
};
class Square :public CalculateArea
{
float length;
public:
Square(float _length = 0):length(_length){}
void Assign()
{
cout << "Please, enter a length: ";
cin >> length;
}
float Calculate()
{
return length*length;
}
};
void Menu()
{
cout << "\nSelect from the following:";
cout << "\nPress 1 for Rectangle"
<< "\nPress 2 for Triangle"
<< "\nPress 3 for Square"
<< "\nPress 0 for Exit";
cout << "\nMake a select: ";
}
int main()
{
CalculateArea* p;
char ch;
do
{
Menu();
cin >> ch;
switch (ch)
{
case '1':
{
Rectangl r;
p = &r;
p->Assign();
cout << "Resulting area is " << p->Calculate();
break;
}
case '2':
{
Triangle t;
p = &t;
p->Assign();
cout << "Resulting area is " << p->Calculate();
break;
}
case '3':
{
Square s;
p = &s;
p->Assign();
cout << "Resulting area is " << p->Calculate();
break;
}
}
} while (ch != '0');
}
Comments
Leave a comment