C++ allows a programmer to manipulate and change the functionality of almost every operator that is used in the standard. This process, known as operator overloading, is a very useful process that allows a programmer to save time and resources whilst writing a code. There are certain rules and conventions that govern the general process of overloading operators in an object oriented paradigm. In this article, I will try and outline these rules and why these were implemented by the creators and pioneers of C++.
The whole concept of operator overloading makes C++ a very useful and malleable language in which to program. A programmer can essentially redefine what the usual operators task is on a specific class and thus can mold all operators in a way as to suit his precise needs.
For example, say we have a class named Fraction whose object possesses a numerator and denominator field. Now, in the real world we know that adding fractions is not the same as just adding integers. Assuming we have two objects of the fraction class called 'obj1' and 'obj2' writing code like:
Fraction obj3 =obj1 + obj2;
Would not work unless and until the '+' operator is overloaded or redefined. However once the overloaded function is written, the compiler can recognize and execute all such statements and store the desired result in our obj3.
Operator Overloading: Rules and Conventions:
1. You can only overload those operators that are already supported by the standard. Thus made-up symbols (such as ' " ' or ' @ ') may not be overloaded.
2. Existing operators cannot be combined and made into new symbols. For example, '-+' may not be used.
3. All operators used in C++ can be overloaded with the exception of six. These are '?: ', ' sizeof ', '.* ', ':: ', '. ' and ' typeid ' operators.
4. You cannot change the precedence or associativity level of the operators by overloading them. This will be the same as already predefined in the language standard.
5. All inherited classes automatically inherit all overloaded operators except for the assignment operator.
6. No default parameters can be passed to overloaded operator functions.