How to use dynamic allocation object and polymorphism in C++

1 Answer

0 votes
#include <iostream>

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

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

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

class Triangle : public Shape {
public:
	float area(void) {
		return (width * height / 2.0);
	}
};

int main() 
{
	Shape *prect = new Rectangle;
	Shape *ptri = new Triangle;
	
	prect->set(3, 7);
	prect->print();

	ptri->set(3, 7);
	ptri->print();

	delete prect;
	delete ptri;

	return 0;
}


/*
run:

21
10.5

*/

 



answered Mar 10, 2018 by avibootz
...