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.


Most operators can be redefined, there are restrictions.