How to calculate area of rectangle and kite using polymorphism abstract class and pure virtual function in C++

2 Answers

0 votes
#include <iostream>

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

class Shape {
protected:
	float width, height;
public:
	void init(float w, float h)
	{
		width = w; height = h;
	}
	virtual float area() = 0;
};

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

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


int main()
{
	Rectangle rect;
	kite kt;
	// Shape sp; // Error C2259 'Shape': cannot instantiate abstract class


	Shape *prect = &rect;
	Shape *pkt = &kt;

	prect->init(7, 3);
	pkt->init(7, 3);

	cout << rect.area() << endl;
	cout << kt.area() << endl;

	return 0;
}

/*
run:

21
10.5

*/

 



answered Feb 17, 2018 by avibootz
edited Feb 17, 2018 by avibootz
0 votes
#include <iostream>

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

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

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

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


int main()
{
	Rectangle rect;
	kite kt;

	Shape *prect = &rect;
	Shape *pkt = &kt;

	prect->init(7, 3);
	pkt->init(7, 3);

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

	return 0;
}

/*
run:

21
10.5

*/

 



answered Feb 17, 2018 by avibootz
edited Feb 17, 2018 by avibootz

Related questions

2 answers 286 views
1 answer 211 views
1 answer 178 views
3 answers 193 views
193 views asked Jan 29, 2023 by avibootz
1 answer 163 views
1 answer 187 views
...