Lesson 2 | Why overload operators? |
Objective | Understand why operator overloading is useful in C++. |
Reason behind Operator Overloading in C++
Just as a function name, such as 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 (/).
All of the arithmetic operators are binary operators and all four of these operators are overloaded in the exact same way.
Operator overloading allows operators to be redefined and used where one or both of the operands are of a user-defined class.
When done correctly, this can simplify the code and make user-defined types as easy to use as the primitive types.
Operator overloading example
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);