The links posted above are all helpful in some regard. Something you should consider though, is that in C++ operator overloading is exactly the same as function overloading. Remember that the compiler will always try to implicitely convert code like
c = a + b;
into something like this
operator=(c,operator+(a,b));
As you can see, the second form uses standard function calls, and the names of these functions are
operator=
and
operator+
, respecticely.
For many built-in types, such as int or float, these operator functions have a default implementation. Also, the compiler will automatically define
operator=
for every struct or class that you define, unless you define it yourself (or prevent it by some compiler setting).
The main use of self-defined overloaded operators is for readability: if you have a class that represents objects which in a real world context could be combined with other objects using the symbols that are commonly used for operators, then it makes sense to define an operator function for your class that performs exactly this function.
For instance if you have 2D-Points P1 and P2 on your screen, you might want to express the vector from P1 to P2 like this:
V = P1 - P2
. If you define a class for a 2D-point however, the compiler will not understand this expression - you first have to define the
operator-
like this:
class Point2 {
public:
int x;
int y;
};
Point2 operator-(const Point2& p1, const Point2& p2) {
Point2 v;
v.x = p1.x-p2.x;
v.y = p1.y-p2.y;
return v;
}