Answer to Question #196634 in C++ for fhjulkjmnbn

Question #196634

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) 



1
Expert's answer
2021-05-21T10:52:29-0400
#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;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog