Area of Circle square triangle using circle using runtime polumorphism


[/code]
Last edited on
You never call show_info() which is a bit weird name for getting input...
And you have no virtual functions. Polymorphism is very much about all Shapes being Shapes, but some Shapes behaving a bit more roundish way.

Consider this:
1
2
3
4
5
6
7
8
9
10
void test( const Shape& s ) {
  s.display();
}

int main()
{   
  // create object x

 test( x );
}

The x could be Triangle or Square or Circle, but the test() should not need to know that.
Alas, your class Shape does not have member display() const.
The issue with having Shape() obtain 2 values is that for square and circle you only need one value. Perhaps a simple way without using polymorphism is:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#define _USE_MATH_DEFINES
#include <iostream>
#include <cmath>
#include <string>
using namespace std;

class Shape {
public:
	double a {}, b {};

	Shape(const string& txt, bool ask2 = false) {
		cout << txt;
		getData(ask2);
	}

protected:
	void getData(bool ask2 = false) {
		if (ask2) {
			cout << "Enter 2 values: ";
			cin >> a >> b;
		} else {
			cout << "Enter value: ";
			cin >> a;
		}
	}
};

class Triangle : public Shape {
public:
	Triangle() : Shape("For triangle, ", true) {}

	void display() const {
		cout << "Area of triangle " << 0.5 * a * b << '\n';
	}
};

class Square : public Shape {
public:
	Square() : Shape("For square, ") {}

	void display() const {
		cout << "Area of Square " << a * a << '\n';
	}
};

class Circle : public Shape {
public:
	Circle() : Shape("For circle, ") {}

	void display() const {
		cout << "Area of Circle " << M_PI * a * a << '\n';
	}
};

int main()
{
	Triangle t;
	t.display();

	Square s;
	s.display();

	Circle c;
	c.display();
}



For triangle, Enter 2 values: 4 5
Area of triangle 10
For square, Enter value: 5
Area of Square 25
For circle, Enter value: 3
Area of Circle 28.2743

Last edited on
The OP has removed the original post. Ahhhhhhh...
Topic archived. No new replies allowed.