Answer to Question #192878 in C++ for Sankalp

Question #192878

Create a base class called Shape. Use this class to store two double values that could beused to compute the area of figures. Derive three classes called as triangle, rectangle andcircle from the base Shape.Add to the base class a member function get_data() to initialize base class datamembers and another member function display_area() to compute and display the area offigures. Make display_area() as a virtual function and redefine this function in the derivedclasses to suit their requirements.Using these four classes, design a program that will accept, dimensions of a triangleand rectangle and radius of circle, and display the area.The two values given as input willbe treated as lengths of two sides in the case of rectangles and as base and height in thecase of triangles and used as follows :Area of rectangle = x * yArea of triangle = ½ * x * y

1
Expert's answer
2021-05-15T02:25:32-0400
#include <iostream>
#include <string>
using namespace std;


class Shape
{
public: 
	
	double a,b;
	void get_data (){
		cout<<"Enter a = ";
		cin>>a;
		cout<<"Enter b = ";
		cin>>b;
	}
	virtual void display_area (){
		cout<<"a = "<<a<<"\n";
		cout<<"b = "<<b<<"\n";
	}
};


class Triangle:public Shape
{
public: 
	void display_area (){
		Shape::display_area();
		double area=0.5*a*b;
		cout<<"Area of triangle "<<area<<endl;
	}
};




class Rectangle:public Shape
{
public: 
	void display_area (){
		Shape::display_area();
		double area=a*b;
		cout<<"Area of rectangle: "<<area<<endl;
	}
};


class Circle:public Shape
{
public:
	void display_area (){
		Shape::display_area();
		double area=3.14*a*b;
		cout<<"Area of Circle: "<<area<<endl;
	}
};


int main()
{	
	Triangle triangle;
	Shape *shape = &triangle;
	cout<<"Enter (a is base, b is height) of the triangle:\n";
	shape->get_data();
	shape->display_area();




	Rectangle rectangle;
	shape = &rectangle;
	cout<<"Enter lengths of two sides of the rectangle:\n";
	shape->get_data();
	shape->display_area();




	Circle circle;
	shape = &circle;
	cout<<"Enter (a and b are the radius) of the circle:\n";
	shape->get_data();
	shape->display_area();






	system("pause");
	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