Operator Overloading in C++
In C++, we can make operators to work for user defined classes. This means C++ has the ability to provide the operators with a special meaning for a data type, this ability is known as operator overloading.
For example, we can overload an operator ‘+’ in a class like String so that we can concatenate two strings by just using +.
Other example classes where arithmetic operators may be overloaded are Complex Number, Fractional Number, Big Integer, etc.
A simple and complete example
12 + i9
What is the difference between operator functions and normal functions?
Operator functions are same as normal functions. The only differences are, name of an operator function is always operator keyword followed by symbol of operator and operator functions are called when the corresponding operator is used.
Following is an example of global operator function.
Can we overload all operators?
Almost all operators can be overloaded except few. Following is the list of operators that cannot be overloaded.
. (dot) :: ?: sizeof
Why can’t . (dot), ::, ?: and sizeof be overloaded?
See this for answers from Stroustrup himself.
Important points about operator overloading
1) For operator overloading to work, at least one of the operands must be a user defined class object.
2) Assignment Operator: Compiler automatically creates a default assignment operator with every class. The default assignment operator does assign all members of right side to the left side and works fine most of the cases (this behavior is same as copy constructor). See this for more details.
3) Conversion Operator: We can also write conversion operators that can be used to convert one type to another type.
Overloaded conversion operators must be a member method. Other operators can either be member method or global method.
4) Any constructor that can be called with a single argument works as a conversion constructor, means it can also be used for implicit conversion to the class being constructed.
x = 20, y = 20 x = 30, y = 0
We will soon be discussing overloading of some important operators like new, delete, comma, function call, arrow, etc.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.