Operator Overloading

Operator overloading allows us to have our classes work with the C++ standard operators, such as +, <<. and >>. This has the effect of making our classes more natural to use and they feel like part of the language.

  • Just because we can overload an operator, it doesn’t mean we should.

Operator overloading can be done two ways, as a member method and as a function. Taking the binary + operator on a point as an example, we declare the method as

Point operator+(const Point &rhs) const;

where rhs means right hand side. And we declare the function as

Point operator+(const Point &lhs, const Point &rhs);

where lhs means left hand side and rhs means right hand side. External functions for operator overloads are normally declared as friends. These are both called as

Point point = existing_point1 + existing_point2;

For the unary operators, using the ++ prefix operator as an example, we call the member function as follows

Point operator++();

and we call the non-member function as follows

Point operator++(Point &p);

As to whether you should use member or non-member functions, that is mostly a matter of stylistic choice. Just be consistent. There are a few exceptions though. The stream insertion and extraction operators, for example, should be declared as a non-member function. This is because declaring it as a member function makes using it unnatural. For example, sending our point to the standard output stream would be

my_point << std::cout;

which is definitely the wrong way round. The subscript operator must be declared as a member function.

Custom conversion overloads can also only be done as member functions. Writing them as non-member functions will generate a compiler error. Note that they have no return type.

operator double() const;

You can also use a constructor to convert between types. Some compilers will generate an error if you have both.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.