Operator overloading is syntactic sugar, and is used because it allows programming using notation nearer to the target domain^{[1]} and allows userdefined types a similar level of syntactic support as types built into a language. It is common, for example, in scientific computing, where it allows computing representations of mathematical objects to be manipulated with the same syntax as on paper.
Operator overloading does not change the expressive power of a language (with functions), as it can be emulated using function calls. For example, consider variables a, b, c
of some userdefined type, such as matrices:
a + b * c
In a language that supports operator overloading, and with the usual assumption that the ‘*’ operator has higher precedence than ‘+’ operator, this is a concise way of writing:
add (a, multiply (b,c))
However, the former syntax reflects common mathematical usage.
As unary operators can be overloaded, we can also overload binary operators. Syntax for overloading a binary operator using a member function is as follows:
1
2
3
4
5

return–type operator op(ClassName &)
{
//Body of function
...
}

Syntax for overloading a binary operator using a friend function is as follows:
1
2
3
4
5

return–type operator op(ClassName &, ClassName &)
{
//Body of function
...
}

Following program demonstrates overloading the binary operator + using a member function:
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

#include <iostream>
using namespace std;
class Number
{
private:
int x;
public:
Number() {}
Number(int x)
{
this>x = x;
}
Number operator +(Number &n)
{
Number temp;
temp.x = x + n.x;
return temp;
}
void display()
{
cout<<“x = “<<x<<endl;
}
};
int main()
{
Number n1(20);
Number n2(10);
Number n3 = n1 + n2;
n3.display();
return 0;
}
Output of the above program is as follows:
x = 30

Following program demonstrates overloading the binary operator + using a friend function:
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

#include <iostream>
using namespace std;
class Number
{
private:
int x;
public:
Number() {}
Number(int x)
{
this>x = x;
}
friend Number operator +(Number &, Number &);
void display()
{
cout<<“x = “<<x<<endl;
}
};
Number operator +(Number &n1, Number &n2)
{
Number temp;
temp.x = n1.x + n2.x;
return temp;
}
int main()
{
Number n1(20);
Number n2(10);
Number n3 = n1 + n2;
n3.display();
return 0;
}
Output of the above program is as follows:
x = 30

Note: Operators such as =, ( ), [ ], and > cannot be overloaded using friend functions.
Take your time to comment on this article.