Objects-Value Operations
Overloading an operator by using a non-member friend function turns out to be
necessary when the left operand is not an object but a constant value:
obj2 = 3 - obj1;
In this case, overloading using a member operator function wouldn't work, as the
overloading function cannot be called by the left hand operand. Further, such
an operand would not be able to be passed to the function through this.
On the other hand, in friend-function overloading both operands are passed as
arguments, so any situation can be dealt with - for example, the aforementioned
operation involving an object and a constant value (and the other way around):
3 - obj1;
obj1 - 3;
can be dealt with by writing two different friend operator functions.
The compiler will pick the appropriate one for any situation.
Example
#include <iostream>
using namespace std;
class Degrees // can store an angle value.
{
int angle;
public:
void setAngle(int x)
{
angle = x%360;
}
int getAngle()
{
return angle;
}
friend Degrees operator-(Degrees leftOperand, int anAngle);
friend Degrees operator-(int anAngle, Degrees rightOperand);
};
// - is overloaded, two parameters are passed: an int and a Degrees object
Degrees operator-(Degrees leftOperand, int anAngle)
{
Degrees temp;
temp.angle = (leftOperand.angle - anAngle)%360;
return temp;
}
// - is overloaded, two parameters are passed: a Degrees object and an int
Degrees operator-(int anAngle, Degrees rightOperand)
{
Degrees temp;
temp.angle = (anAngle - rightOperand.angle)%360;
return temp;
}
int main()
{
Degrees obj1;
Degrees obj2;
obj1.setAngle(31);
obj2 = 50 - obj1; // 50 - 31 = 19
cout << obj2.getAngle() << endl;
obj2 = obj1 - 10; // 31- 10 = 21
cout << obj2.getAngle() << endl;
}
Output
19
21