-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathoops_polymorphism.cpp
95 lines (80 loc) · 1.55 KB
/
oops_polymorphism.cpp
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
#include <iostream>
#include <cmath>
using namespace std;
// C++ polymorphism means that a call to a
// member function will cause a different function
// to be executed depending on the type of object
// that invokes the function.
// virtual functions tell the compiler to "direct" the
// method call based on the object that called it.
// we have to declare virtual because of static binding by
// the compiler
class Shape
{
protected:
int width;
int height;
public:
Shape(int a = 0, int b = 0)
{
width = a;
height = b;
}
virtual int area()
{
cout << "Parent class area method: " << width * height << endl;
return width * height;
}
};
class Rectangle : public Shape
{
public:
Rectangle(int w, int h)
{
this->width = w;
this->height = h;
}
int area()
{
cout << "Rectangle class area: " << width * height << endl;
return width * height;
}
};
class Triangle : public Shape
{
public:
Triangle(int w, int h)
{
this->width = w;
this->height = h;
}
int area()
{
cout << "Trianle class area: " << 0.5 * width * height << endl;
return 0.5 * width * height;
}
};
class Circle
{
private:
int radius;
public:
Circle(int r)
{
radius = r;
}
float area()
{
return (0.5) * (3.14) * (pow(radius, 2));
}
};
int main()
{
Shape *shape;
Shape shp(11, 11);
Rectangle rect(12, 12);
Triangle tri(13, 13);
shape = &tri;
shp.area();
shape->area();
}