-
Notifications
You must be signed in to change notification settings - Fork 0
/
polymorphism.cpp
64 lines (51 loc) · 1.35 KB
/
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
#include <iostream>
using namespace std;
class Shape {
protected:
int width, height;
public:
Shape(int a = 0, int b = 0) {
width = a;
height = b;
}
virtual int area() {
cout << "Parent class area :" << endl;
return 0;
}
// if we do not put virtual, the output in main will be "Parent class area :" its called static resolution. The compiler sets it at the base case. (its looks only the object
// Shape and not the pointer).
// however with the virtual keywork, the compiler look the value of its pointer instead of its type. (thats why theres the Shape *shape in main)
// virtual tells the compiler not to use static resolution ~ish
};
class Rectangle : public Shape {
public:
Rectangle(int a = 0, int b = 0) :Shape(a, b) { }
int area() {
cout << "Rectangle class area :" << endl;
return (width * height);
}
};
class Triangle : public Shape {
public:
Triangle(int a = 0, int b = 0) :Shape(a, b) { }
int area() {
cout << "Triangle class area :" << endl;
return (width * height / 2);
}
};
int main() {
Shape *shape;
Rectangle rec(10, 7);
Triangle tri(10, 5);
// store the address of Rectangle
// Note: I can store &rec in shape since &rec inherites shape
shape = &rec;
// call rectangle area.
shape->area();
// store the address of Triangle
shape = &tri;
// call triangle area.
shape->area();
system("pause");
return 0;
}