-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathoperatorOverloading.cpp
76 lines (66 loc) · 1.57 KB
/
operatorOverloading.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
/*
* Program to understand operator overloading
*/
#include <iostream>
using namespace std;
class Box {
private:
int length;
int breadth;
int height;
public:
void setLength(int len) {
length = len;
}
void setBreadth(int br) {
breadth = br;
}
void setHeight(int h) {
height = h;
}
int getVolume() {
int vol = length*breadth*height;
return vol;
}
// overload '+' operator to add two boxes
// SYNTAX:
// className operator + (const className &obj);
Box operator + (const Box &b) {
Box result;
result.length = this->length + b.length;
result.breadth = this->breadth + b.breadth;
result.height = this->height + b.height;
return result;
}
friend istream &operator >> (istream &cin, Box &b);
};
// if you were to overload + operator without creating a member function
// Box operator + (const Box &b1, const Box &b2) ;
// to overload input/output functions, need to create friend functions
istream &operator >> (istream &cin, Box &b) {
cout << "Enter the length: ";
cin >> b.length;
cout << "Enter the breadth: ";
cin >> b.breadth;
cout << "Enter the height: ";
cin >> b.height;
return cin;
}
int main () {
Box b1, b2, b3;
b1.setLength(5);
b1.setBreadth(6);
b1.setHeight(7);
cout << "Box volume of b1: " << b1.getVolume() << endl;
b2.setLength(3);
b2.setBreadth(3);
b2.setHeight(7);
// b1 is invoking the + operator
// b2 is the object being passed as argument to '+' function
b3 = b1 + b2;
cout << "Box volume of b3: " << b3.getVolume() << endl;
Box b4;
cin >> b4;
cout << "Box b4's volume is: " << b4.getVolume() << endl;
return 0;
}