Create a base class called Shape which has two double type values. Use member functions get()
and set() to get and set the values. Use a virtual function display_area() to display the area. Derive
two specific classes called Triangle and Rectangle from the base class Shape. Redefine
display_area() in the derived classes. Write a program to display the rectangle or triangle area.
#include <iostream>
#include <cmath>
using namespace std;
class Shape
{
private:
double length,width;
public:
Shape(double a, double b) {
length = a;
width = b;
}
double getLength() {return length; }
double getWidth() {return width; }
void setLength(double a) {length = a;}
void setWidth(double b) {width = b;}
virtual void display_area() {cout << length * width;}
};
class Triangle : public Shape {
private:
double c;
public:
Triangle(double a, double b, double bar) : Shape(a, b) { c = bar;}
void display_area() {
double p = (this->getLength()+ this->getWidth()+c)/2;
double area = sqrt(p*(p-this->getWidth())*(p-this->getLength())*(p-c));
cout << "Area of the triangle: " << area << '\n';
}
};
class Rectangle : public Shape
{
public:
Rectangle(double a, double b) : Shape(a, b) {}
void display_area() {
cout << "The area of the rectangle: " << this->getLength()*this->getWidth() << '\n';
}
};
int main()
{
Triangle triangle = Triangle(3,4,5);
triangle.display_area();
Rectangle rect = Rectangle(3,4);
rect.display_area();
return 0;
}
Output:
Area of the triangle: 6
The area of the rectangle: 12
Comments
Leave a comment