Overload Binary Operator using Member Function


Binary operator having two operands so generally we need to pass two arguments to the operator function.
If you define operator function as a member function then it will accept one argument. Because the object that is used to invoke the operator function is passed implicitly to the operator function and other object is passed explicitly to the function.
Consider following example to overload binary operator + using member function.

#include <iostream.h>
class demo
{
int x,y;
public:
demo()
{
x=0;
y=0;
}
demo(int a, int b)
{
x=a;
y=b;
}
demo operator +(demo &d)
{
demo d3;
d3.x = x + d.x;
d3.y = y + d.y;
return d3;
}
void display()
{
cout<<"X="<<x<<endl;
cout<<"Y="<<y<<endl;
}
};
int main()
{
demo d1(2,3);
demo d2(4,5);
demo d3;
d3 = d1 + d2;
cout<<"Object C1\n";
d1.display();
cout<<"Object C2\n";
d2.display();
cout<<"Object C3\n";
d3.display();
return 0;
}
Output:
Object C1
X=2
Y=3
Object C2
X=4
Y=5
Object C3
X=6
Y=8


     

Overload Binary Operator using Friend Function


If you define operator function as a friend function then it will accept two arguments. Because friend functions is not a member function so it is not invoked using object of the class. Thus we need to pass two objects as an argument explicitly.
Consider following example to overload binary operator + using friend function.

#include <iostream.h>
class demo
{
int x,y;
public:
demo()
{
x=0;
y=0;
}
demo(int a, int b)
{
x=a;
y=b;
}
friend demo operator + (demo &d1, demo &d2)
{
demo d3;
d3.x = d1.x + d2.x;
d3.y = d1.y + d2.y;
return d3;
}
void display()
{
cout<<"X="<<x<<endl;
cout<<"Y="<<y<<endl;
}
};
int main()
{
demo d1(2,3);
demo d2(4,5);
demo d3;
d3 = operator + (d1,d2);
cout<<"Object C1\n";
d1.display();
cout<<"Object C2\n";
d2.display();
cout<<"Object C3\n";
d3.display();
return 0;
}
Output:
Object C1
X=2
Y=3
Object C2
X=4
Y=5
Object C3
X=6
Y=8

Download Projects


Download Programs