Rules for Overloading Operators
- Overloading of an operator cannot change the basic idea of an operator. When an operator is overloaded, its properties like syntax, precedence, and associatively remain constant. For example A and B are objects. The following statement
- Overloading of an operator must never change its natural meaning. An overloaded operator + can be used for subtraction of two objects, but this type of code decreases the utility of the program. Remember that the aim of operator overloading is to comfort the programmer to carry various operations with objects. Consider the following program:
10.18 Misuse of operator overloading. Perform subtraction using + operator.
Explanation: In the above program, the operator + is overloaded. It performs subtraction. Such type of misuse must be avoided while overloading operators. The programmer thought that it would perform addition, but in reality it performs subtraction.
- The overloaded operator should contain one operand of user-defined data type. Overloading operators is only for classes. We cannot overload the operator for built-in data types.
- Overloaded operators have the same syntax as the original operator. They cannot be prevailing over the original operators.
- There is no higher limit to the number of overloading for any operator. An operator can be overloaded for a number of times if the arguments are different in each overloaded operator function.
- Operator overloading is applicable within the scope (extent) in which overloading occurs.
- Only existing operators can be overloaded. We cannot create a new operator.
- C++ has a wide range of operators. However, few operators cannot be overloaded to operate in a same manner like built-in operators. The operators given in Table 10.1 cannot be overloaded.
For example, operators such as ?:, ::, and .* are combinations of more than one symbol. The condition operator needs three arguments. It is only one operator that requires three arguments. Hence, the above operators cannot be overloaded.
- The operators given in Table cannot be overloaded using friend function.
- When unary operator is overloaded using member functions, it requires no explicit friend argument and returns no values. When it is overloaded using friend function, it requires one reference argument.
- When binary operator is overloaded using friend function, it requires two arguments. When it is overloaded using member function, it requires one argument.