How to calculate area of rectangle and kite using dynamic allocation and polymorphism in C++

1 Answer

0 votes
#include <iostream>

using std::cout;
using std::endl;

class Shape {
protected:
	float width, height;
public:
	Shape(float w, float h) : width(w), height(h) {}
	virtual float area() = 0;
	void printArea()
	{
		cout << this->area() << endl;
	}
};

class Rectangle : public Shape {
public:
	Rectangle(float w, float h) : Shape(w, h) {}
	float area()
	{
		return width * height;
	}
};

class kite : public Shape {
public:
	kite(float w, float h) : Shape(w, h) {}
	float area()
	{
		return (width * height) / 2;
	}
};


int main()
{
	Shape *prect = new Rectangle(7, 3);
	Shape *pkt = new kite(7, 3);

	prect->printArea();
	pkt->printArea();

	delete prect;
	delete pkt;

	return 0;
}

/*
run:

21
10.5

*/

 



answered Feb 17, 2018 by avibootz

Related questions

...