Operator Overloading Intro
Overloading an operator means to make it perform a special operation once it is
applied to one or more objects of a specific class. The actions performed by an
overloaded operator are specified by an operator function.
The operator function can be a member of the class of objects it can be applied
to. In this case, the operator function takes the following form:
returnType operatorX(operands)
{
// body
}
returnType can be any type, although most
times it will be the same type as the
operands;
X is the operator,
operands
are the operands involved in the operation but the leftmost one. So if the
operator is binary, the parameter list will contain just one operand.
For a unary operator, the list will be empty.
NB. The object that actually calls the operator function is the left operand.
Such an operand is passed to the function by means of the this pointer.
For example, in the expression:
obj1 + obj2
obj1 calls the operator function and can be
accessed to through the
this pointer, while
obj2 is passed as an argument to the function.
Further, notice that when overloading an operator, the number of operands it
takes cannot be changed.
And finally, overloaded operators are all inherited by derived classes, but the
=.
Example
#include <iostream>
using namespace std;
class Degrees
{
int angle;
public:
void setAngle(int x)
{
angle = x % 360;
}
int getAngle()
{
return angle;
}
Degrees operator+(Degrees rightOperand); // left-side operand is
//passed through this, rightOperand contains the operand on the right side.
Degrees operator=(Degrees rightOperand);
Degrees operator++();
};
Degrees Degrees::operator+(Degrees rightOperand)
{
Degrees temp;
temp.angle = (rightOperand.angle + angle) % 360; // angle refers to the
// object calling the operator function: the left operand
return temp;
}
Degrees Degrees::operator=(Degrees rightOperand)
{
angle = rightOperand.angle;
return *this; // the object calling the function is the one on the
// left. The function is called through this: this->operator=. So by
// returning *this the left operand’s value is returned
}
Degrees Degrees::operator++()
{
angle = (angle++)%360;
return *this; // the left operand is returned
}
int main()
{
Degrees obj1;
Degrees obj2;
Degrees obj3;
obj1.setAngle(190);
obj2.setAngle(200);
obj3 = obj1 + obj2; // objects are added and assigned
++obj3;
cout << obj3.getAngle() << endl;
cout << (obj1 + obj2).getAngle() << endl;
}
Output
31
30
In fact, 200+190 = 390 degrees, which is equivalent to 30 degrees.