Answer to Question #247970 in C++ for SOM

Question #247970

Create a base class called Shape with two data members of double type

which could be used to compute the area of figures. Derive two specific

classes called Triangle and Rectangle from the base class Shape. Add to the

base class, a member function called Get Data to initialize base class data

members and another member function display Area to compute and display

the area of figures. Make display Area a virtual function and redefine this

function in the derived classes to suit their requirements. Using these three

classes design a program which will accept dimensions of a triangle or

rectangle interactively and display the area.


1
Expert's answer
2021-10-08T17:10:08-0400
#include <iostream>


using namespace std;




class Shape
{
protected:
	//has two double type values.
	double height,base;
public:
	//constructor to assign initial values to height and base
	Shape(){
		this->height=0;
		this->base=0;
	}


	void GetData(){
		cout<<"Enter height: ";
		cin>>height;
		cout<<"Enter base: ";
		cin>>base;
	}
	
	double geHeight(){
		return height;
	}
	double geBase(){
		return base;
	}


	virtual void Area(){}
};


//class triangle inheriting class Shape
class Triangle : public Shape
{
public:
	void Area()
	{
		cout<<"Height: "<<height<<"\n";
		cout<<"Base: "<<base<<"\n";
		cout<<"Area of Triangle = "<<(height*base)/2;
	}
};


//class Rectangle inheriting class Shape
class Rectangle : public Shape
{
public:


	void Area()
	{
		cout<<"Side a: "<<height<<"\n";
		cout<<"Side b: "<<base<<"\n";
		cout<<"Area of Rectangle = "<<(height*base);
	}
};
void main(){
	Shape *shape;
	Triangle triangle;
	triangle.GetData();
	shape=&triangle;
	shape->Area();
	Rectangle rectangle;
	cout<<"\n\n";
	rectangle.GetData();
	shape=&rectangle;
	shape->Area();
	cout<<"\n\n";
	system("pause");
}

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
APPROVED BY CLIENTS