Overloading An Operator Using A friend Function

Another way to overload operators is by using a non-member operator function (typically a friend function, in order to have access to the private members of the class the operator applies to). When a non-member operator function is used, the number of parameters must match the number of operands involved in the operation. Also, in unary operations, like ++, the only argument is passed by reference. In the following program both the + operator and ++ are overloaded, as both prefix and suffix. NB in this example the postfix version returns a new object which is a copy of the object the ++ operator is applied to, before the operator is applied.

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;
     }

     // operator functions
     friend Degrees operator+(Degrees leftOperand, Degrees rightOperand);
     friend Degrees operator++(Degrees &operand);
     friend Degrees operator++(Degrees &operand, int postfix);
};
 
// + is overloaded, two parameters are passed
Degrees operator+(Degrees leftOperand, Degrees rightOperand)
{
     Degrees temp;
     temp.angle = (leftOperand.angle + rightOperand.angle)%360;
     return temp;
}

Degrees operator++(Degrees &operand)  // prefix version
{
     operand.angle = (operand.angle + 1)%360;
     return operand;   // operand is returned
}

Degrees operator++(Degrees &operand, int postfix)  // postfix version
{
     Degrees returnedObject = operand;
     operand.angle = (operand.angle + 1)%360;
     return returnedObject;   // operand is returned
}

int main()
{   
     Degrees obj1;
     Degrees obj2;
     obj1.setAngle(31);
     obj2.setAngle(350); 
     cout << (obj1 + obj2).getAngle() << endl;
     ++obj1;
     cout << obj1.getAngle() << endl;
     Degrees anotherObj = obj1++;
     cout << obj1.getAngle() << endl;
     cout << anotherObj.getAngle() << endl;
}

Output

21
32
33
32