# C++ Notes: Operator Overloading

## Why overload operators

Clarity. It's common to define a meaning for an existing operator for objects of a new class. Operators are defined as either member functions or friend functions. Don't use operator overloading just because it can be done and is a clever trick. The purpose of operator overloading is to make programs clearer by using conventional meanings for `==`, `[]`, `+`, etc.

For example, overloading the `[]` operator for a data structure allows `x = v[25]` in place of a function call. This is purely a conveniece to the user of a class. Operator overloading isn't strictly necessary unless other classes or functions expect operators to be defined (as is sometimes the case).

Whether it improves program readability or causes confusion depends on how well you use it. In any case, C++ programmers are expected to be able to use it -- it's the C++ way.

## Example - Defining + for Point

Using the Point class, adding (does this make sense?) can be defined like this:

    //=== Point.h file =============================
        Point operator+(Point p) const;

    //=== Point.cpp file ===========================
    Point Point::operator+(Point p) const {
          return Point(x+p.x,  y+p.y);
    }

    //=== myprogram.cpp ============================
    Point a(10, 20);
    Point b(1, 2);
    Point c = a + b;

## Define a function which begins with the "operator" keyword

Define a function with the keyword "operator" preceding the operator. There can be whitespace between `operator` and the operator, but usually they are written together.

## Restrictions

Most operators can be redefined, there are restrictions.

- It's not possible to change an operator's precedence.
- It's not possible to create new operators, eg `**` which is used in some languages for exponentiation.
- You may not redefine `::`, `sizeof`, `?:`, or `.` (dot).
- Overloading `+` doesn't overload `+=`, and similarly for the other extended assignment operators.
- `=`, `[]`, and `->` must be member functions if they are overloaded.
- `++` and `--` need special treatment because they are prefix and postfix operators.
- There are special issues with overloading assignment (=) (see Overloading Assignment). Assignment should always be overloaded if an object dynamically allocates memory.