Answer to Question #213785 in C++ for Hemambar

Question #213785

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.


1
Expert's answer
2021-07-11T14:37:47-0400
#include <iostream>
#include <string>
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 set(){
		cout<<"Enter height: ";
		cin>>height;
		cout<<"Enter base: ";
		cin>>base;
	}
	//get() function to get values
	double geHeight(){
		return height;
	}
	double geBase(){
		return base;
	}


	//declaration of virtual function display_area()
	virtual void display_area(){}
};


//class triangle inheriting class Shape
class Triangle : public Shape
{
public:


	//redefining function display_area()
	void display_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:


	//redefining function display_area()
	void display_area()
	{
		cout<<"Side a: "<<height<<"\n";
		cout<<"Side b: "<<base<<"\n";
		cout<<"Area of Rectangle = "<<(height*base);
	}
};
void main(){
	Shape *shape;
	Triangle triangle;
	triangle.set();
	shape=&triangle;
	shape->display_area();
	Rectangle rectangle;
	cout<<"\n\n";
	rectangle.set();
	shape=&rectangle;
	shape->display_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