-
Notifications
You must be signed in to change notification settings - Fork 0
/
Object Oriented Programming.cpp
119 lines (96 loc) · 2.13 KB
/
Object Oriented Programming.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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
#include <iostream>
#include <string>
using namespace std;
//Base Class
class Shape
{
protected:
string name;
public:
Shape(string s)
{
name = s;
}
void setName(string s)
{
name = s;
}
string getName() const
{
return name;
}
virtual double getArea() const = 0; // assign 0 to make pure virtual function. Note how no variables declared for different shapes
};
// first child class
class Circle : public Shape // don't have to re-write Base Class declarations
{
double radius;
public:
Circle(string n, double r) : Shape(n)
{
radius = r;
}
void setRadius(double r)
{
radius = r;
}
double getRadius() const
{
return radius;
}
virtual double getArea() const // Feature of polymorphism
{
return 3.14 * radius * radius;
}
};
// Second child class
class Rectangle : public Shape // don't have to re-write Base Class declarations
{
double length, width;
public:
Rectangle(string n, double l, double w) : Shape(n)
{
length = l;
width = w;
}
void setLength(double l)
{
length = l;
}
void setWidth(double w)
{
width = w;
}
double getLength() const
{
return length;
}
double getWidth() const
{
return width;
}
virtual double getArea() const
{
return length * width;
}
};
int main()
{
// Shape s("Foo"); // note how s, c, and r first appear here
// cout << s.getName() << endl;
// had to remove because I added the virtual function
Circle c("Circle", 3.1);
c.setName("Circle TOO");
cout << c.getName() << endl; // shows how getName and getRadius were correctly inherited (compare to rectangle)
cout << c.getRadius() << endl;
cout << c.getArea() << endl;
Rectangle r("Rectangle", 4.2, 2.5);
cout << r.getName() << endl;
cout << r.getWidth() << " " << r.getLength() << endl;
cout << r.getArea() << endl;
// Poloymorphism: can create an arrray of different data types using pointers (each shape, or child class, is a different type)
Shape * shapes[2] = { new Circle("Circle", 2.1), new Rectangle("Rectangle", 3.1, 1.2) };
for (int i = 0; i < 2; i++)
cout << "Shape " << i << " area = " << shapes[i]->getArea() << endl; // dot notation doesn't work because it's a pointer
cin.get();
}