What is Operator Overloading

Operator Overloading enables us to make the standard operators, like +, -, * etc, to work with the objects of our own data types. So what we do is, write a function which redefines a particular operator so that it performs a specific operation when it is used with the object of a class.

Operator overloading does not allow to make new operators or change the precedence of the operator. There are some operators which can not be overloaded.

Operator Description
:: The scope resolution operator
: ? The conditional operator
sizeof The sizeof operator
. The direct member selection operator
.* The de-reference pointer to class member operator

Example of Operator Overloading

C++ allows you to overload operators. This means, for example we can redefine the > operator so that, when it is used with the object of a class ShoeBox, it would return true if the first ShoeBox had the greater volume than the second ShoeBox object.

Here operator< id overloaded for ShoeBox.

Here is the code that shows how we can compare two ShoeBox objects.

And here is the code which actually implements the overloading process.

There are two things to understand here.

  1. We have given the reference parameter to th function to avoid unnecessary copying
  2. As the function does not alter any this so we can declare it as const.

Many books show the syntax for declaring overloaded operators, but few offer guidelines for keeping the amount of code you write to a minimum and for avoiding code duplication. The guidelines in this tutorial do not necessarily result in the most efficient code from an execution standpoint, but development efforts are minimized — efficiency and maintainability from a coding standpoint is emphasized. Of course once you’ve succeed in implementing overloaded operators you can then concentrate on making things efficient.