Answer to Question #325929 in C++ for Prasoon Giri

Question #325929

Create a class called Point which will have 2 co-ordinate value x & y and will be able to 

calculate the distance between two points. Write appropriate constructor and method of the class. 

Create another class called Shape, which takes different number of points to create a triangle, 

rectangle and circle. And also able to calculate the area and perimeter for the different shapes. 

Write the appropriate overloading method for this shape class. Write appropriate main function to 

test the shape class.


1
Expert's answer
2022-04-08T16:06:08-0400
#include<iostream>
#include<cmath>

#define PI 3.14159


using namespace std;

class Point
{
	float x;
	float y;
public:
	Point(float _x, float _y):x(_x),y(_y){}
	Point(Point& p):x(p.x),y(p.y){}
	float Distance(Point& p)
	{
		return sqrt(pow((p.x - x), 2) + pow((p.y - y), 2));
	}
};


class Shape
{
public:
	virtual float Area() = 0;
	virtual float Perimetr() = 0;
};


class Triangle:public Shape
{
	Point a;
	Point b;
	Point c;
public:
	Triangle(Point _a, Point _b, Point _c):a(_a),b(_b),c(_c){}
	float Area()
	{
		float p = Perimetr()/2;
		return sqrt(p*(p - a.Distance(b))*(p - b.Distance(c))*(p - c.Distance(a)));
	}
	float Perimetr()
	{
		return a.Distance(b) + b.Distance(c) + c.Distance(a);
	}
};


class Circle :public Shape
{
	Point a;
	Point b;
public:
	Circle(Point _a, Point _b):a(_a),b(_b){}
	float Area()
	{
		return PI*pow(a.Distance(b), 2);
	}
	float Perimetr()
	{
		return 2 * PI*a.Distance(b);
	}
};


class Rectangl :public Shape
{
	Point a;
	Point b;
	Point c;
	Point d;
public:
	Rectangl(Point _a, Point _b, Point _c,Point _d) : a(_a), b(_b), c(_c),d(_d) {}
	float Area()
	{
		return a.Distance(b)*b.Distance(c);
	}
	float Perimetr()
	{
		return a.Distance(b) + b.Distance(c) + c.Distance(d) + d.Distance(a);
	}
};
int main()
{
	Point a(1, 2);
	Point b(1, 5);
	cout << "Distance a b = "<<a.Distance(b)<<endl;
	Point c(8, 5);
	Point d(8, 2);
	Triangle t(a, b, c);
	Circle cir(a, c);
	Rectangl r(a, b, c, d);
	Shape* sh = &t;
	cout << "Triangle`s perimetr is " << t.Perimetr()<<endl;
	cout << "Triangle`s area is " << t.Area() << endl;
	sh = &cir;
	cout << "Circle`s perimetr is " << cir.Perimetr() << endl;
	cout << "Circle`s area is " << cir.Area() << endl;
	sh = &r;
	cout << "Rectangle`s perimetr is " << r.Perimetr() << endl;
	cout << "Rectangle`s area is " << r.Area() << endl;
}

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