Operator overloading allows objects of user-defined types (class/ADT) to be operands for existing operators. This enables convenient syntax on certain operations with objects, for e.g.
If c1,c2 are objects of Complex type, we can write c1+c2 instead of c1.add(c2)
If t1,t2 are Time objects, we can write t1==t2, instead of t1.compare(t2)
This resembles function overloading since the same operator is applicable for different types of user-defined objects and is the basis for compile-time polymorphism.
Here are some points to remember while overloading operators:-
- New operators can’t be created, eg:- **, #, @, $ can’t be overloaded, only existing operators which work on scalar types can be applied on user-defined objects.
- Precedence and associativity remains the same while overloading
- Don’t change the meaning of operators on primitive types, i.e. while overloading +, follow addition rules only, if == returns bool on primitive types, return the same on objects.
- Operators can be overloaded as member functions or global friend functions, where the function name is the concatenation of operator keyword and particular symbol, eg:- operator+, operator=, operator++, etc.
- The following operators can’t be overloaded at all
. (dot operator)
:: (Scope resolution operator)
.* (member access through pointer to member functions)
?: (conditional operator)
- The following operators can’t be overloaded as a friend function
= (Assignment operator)