Answer to Question #248118 in C++ for Julian

Question #248118

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 GetData to initialize base class data

members and another member function displayArea to compute and display

the area of figures. Make displayArea 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-09T04:45:22-0400
#include<iostream>
using namespace std;
class Shape
{
	public: 
	double first,second;
		void getData ()
		{
			cin>>first>>second;
		}
		virtual void displayArea () = 0;
};


class Triangle:public Shape
{
	public: void displayArea ()
	{
		cout<<"The area of Triangle:  "<<0.5*first*second<<endl;
	}
};


class Rectangle:public Shape
{
	public:
	 void displayArea ()
	{
		cout<<"The area of the Rectangle:  "<<first*second<<endl;
	}
};


int main()
{	
	Triangle triangle;
	Shape *shape_triangle = &triangle;
	cout<<"Enter base and height: ";
	shape_triangle->getData();
	shape_triangle->displayArea();
	
	Rectangle rec;
	Shape *shape_rect = &rec;
	cout<<"Enter length and width: ";
	shape_rect->getData();
	shape_rect->displayArea();
	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
APPROVED BY CLIENTS