-
Notifications
You must be signed in to change notification settings - Fork 28
/
Operator_Overloading_UDT_I.cpp
83 lines (65 loc) · 2.11 KB
/
Operator_Overloading_UDT_I.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
#include <bits/stdc++.h>
using namespace std;
/*
Operator overloading for UDT - I (UDT - User Defined Data Type)
Binary (two parameters)
a+b - MyType operaror+(const MyType& a, const MyType& b)
Unary (single parameter)
a++ - MyType operaror++(const MyType& a)
Note :
-The parameters may not be constant and may be passed by by value as well.
-The reutrn type may also be reference or may be constant as well.
-Operator function can be a non-member function as well
--Global function
--Friend function. Ex: friend MyType operaror++(const MyType& a)
When operator function is a member function :
-then binary operator function can have one parameter because second one can be this pointer
-then unary operator function can have 0 arguments (with exception post increment operator a++) where we add "int"
int parameter of the function. We don't pass anything, it's just for compiler
Two examples below
*/
//Example - 1 (Add two Complex class objects
class Complex {
double real;
double imag;
public:
Complex(double re, double im): real(re), imag(im) {}
Complex operator+(const Complex& c) {
Complex newC(this->real+c.real, this->imag+c.imag);
return newC;
}
void display() {
cout << "(" << real << " + i" << imag << ")" << endl;
}
};
//Example - 2 (concat two String objects)
class String {
string name;
public:
String(string s): name(s) {}
//Since, it is a member function, hence we are passing only one parameter
String operator+(const String& s) {
String newObj(this->name + "_" + s.name);
return newObj;
}
void display() {
cout << name << endl;
}
};
int main() {
cout << "\nExample - 1\n";
Complex c1(1, 2);
c1.display();
Complex c2(3, 4);
c2.display();
Complex c3 = c1 + c2; //c1.operator+(c2) Binary operator
c3.display();
cout << "\nExample - 2\n";
String s1("Mazhar");
s1.display();
String s2("MIK");
s2.display();
String s3 = s1 + s2; //s1.operator+(s2) Binary operator
s3.display();
return 0;
}