Create a base class called 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 base class, a member function get_data() to initialize base class data members and another member functions display_area() to compute and display the area of figures. Mark the display_area() as a virtual function and redefine this function in the derived class to suit their requirements.(Use pure virtual function)
#include <iostream>
class Shape
{
public:
void get_data(double x, double y) {
m_x = x;
m_y = y;
}
virtual void display_area() = 0;
double m_x{ 0 };
double m_y{ 0 };
};
class Rectangle: public Shape
{
public:
void display_area() {
m_area = m_x * m_y;
std::cout << "Rectangle area: " << m_area << std::endl;
}
private:
double m_area{ 0 };
};
class Triangle : public Shape
{
public:
void display_area() {
m_area = m_x * m_y/2.0;
std::cout << "Triangle right area: " << m_area << std::endl;
}
private:
double m_area{ 0 };
};
int main()
{
// example class test
Rectangle rect_1;
Triangle trian_1;
rect_1.get_data(5, 6);
rect_1.display_area();
trian_1.get_data(3, 4);
trian_1.display_area();
return 0;
}
Comments
Leave a comment