Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 58230ac

Browse files
introduction of operator overloading
1 parent 300cbb0 commit 58230ac

File tree

1 file changed

+54
-0
lines changed
  • Learn_CPP_Programming_Deep_Dive/Section 12 Operator Overloading/Intro_to_operator_overloading

1 file changed

+54
-0
lines changed
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
#include <iostream>
2+
3+
using namespace std;
4+
5+
class Complex
6+
{
7+
public:
8+
int real;
9+
int imaginary;
10+
11+
Complex(int r = 0, int i = 0) : real(r), imaginary(i) //here i am using member initialization lists instead of body assignation
12+
{
13+
cout<<"Parameterized constructor appelead to here -> real part "<<this->real<<" imaginary part "<<this->imaginary<<endl;;
14+
}
15+
16+
/* when defining overloaded operator we offer a new functionality to an operator so that it fits new user defined data types */
17+
Complex add(Complex c)
18+
{
19+
Complex temp;
20+
temp.real = real + c.real;
21+
temp.imaginary = imaginary + c.imaginary;
22+
23+
return temp;
24+
}
25+
26+
/* By replacing the names of the functions to "operator+", "operator-" whatsoever we achieve operator overloading */
27+
Complex operator+(Complex c)
28+
{
29+
Complex temp;
30+
temp.real = real + c.real;
31+
temp.imaginary = imaginary + c.imaginary;
32+
33+
return temp;
34+
}
35+
36+
~Complex()
37+
{
38+
cout<<"This is the destructor of this class"<<endl;
39+
}
40+
};
41+
42+
43+
int main(void)
44+
{
45+
Complex c1(1953,1954), c2(1977,1978), c3,c4;
46+
47+
c3 = c1.add(c2);
48+
c4 = c1 + c2;
49+
50+
cout<<"C3 ="<<c3.real<<"+ i* "<<c3.imaginary<<endl;
51+
cout<<"C4 ="<<c4.real<<"+ i* "<<c4.imaginary<<endl;
52+
53+
return 0;
54+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /