Lesson 2 | Why overload operators? |

Objective | Understand why operator overloading is useful in C++. |

Just as a function name, such as

For example, the expression

The expression

Although meanings can be added to operators, their associativity and precedence remain the same. For example, the multiplication operator will remain of higher precedence than the addition operator.

`print()`

, can be given a variety of meanings that depend on its arguments, so can an operator be given additional meanings. For example, the expression

`a + b`

has different meanings depending on the types of the variables `a`

and `b`

.
Overloading the `+`

operator for user-defined types allows them to be used in addition expressions, in much the same way as a native type.
The expression

`a + b`

could mean string concatenation, complex number addition, or integer addition, depending on whether the variables were the ADT `string`

,
the ADT `complex`

, or the native type `int`

.Although meanings can be added to operators, their associativity and precedence remain the same. For example, the multiplication operator will remain of higher precedence than the addition operator.

Some of the most commonly used operators in C++ are the arithmetic operators.

- the plus operator (+),
- minus operator (-),
- multiplication operator (*), and
- division operator (/).

In the example below there is a class called MyNum with an integer field and a constructor for setting that field. The class also has an addition method that adds two MyNum objects together and returns the result as a new object.

class MyNum{ public: int val; MyNum(int i) : val(i) {} MyNum add(MyNum &a){ return MyNum( val + a.val ); } }

Two MyNum instances can be added together using this method.

MyNum a = MyNum(10), b = MyNum(5); MyNum c = a.add(b);