-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathinheritance.cpp
62 lines (55 loc) · 1.21 KB
/
inheritance.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
/*
* Program to understand inheritance in C++
*/
#include <iostream>
using namespace std;
class Shape2D {
private:
int width;
int height;
public:
int getWidth() {
return width;
}
int getHeight() {
return height;
}
void setWidth(int width) {
this->width = width;
}
void setHeight(int height) {
this->height = height;
}
};
// rectangle and triangle are to be inherited from Shape2D
// SYNTAX:
// class derivedClassName: access-specifier baseClassNames (separated by commas) {};
// public access specifier
// means that all public members of Shape => public of Rectangle
// all protected members of Shape (not any) => protected of Rectangle
class Rectangle: public Shape2D {
public:
int getArea() {
// the inherited getWidth() and getHeight() functions
// can access the private data of shape class
return getWidth() * getHeight();
}
};
class Triangle: public Shape2D {
public:
int getArea() {
// assuming width = base
return 0.5*getWidth()*getHeight();
}
};
int main () {
Rectangle r;
r.setWidth(5);
r.setHeight(5);
cout << "Area of the rectangle is: " << r.getArea() << endl;
Triangle t;
t.setWidth(5);
t.setHeight(10);
cout << "Area of the triangle is: " << t.getArea() << endl;
return 0;
}