There are two types of operators in C++ , Binary (that take 2 operands) and Unary (that take a single operand). Unary operators like ++ or - - and binary operators like +,-, * and / have a predefined task to perform. "+" can add two numericals, ">" can compare a value against other and so on. What if we want the operator to perform a customised task ? For example, using "+" to add to perform multiplication, "==" to function like "!=". How can the functioning of an operator changed ? The answer is - using Operator Overloading.Using this concept an operator can be made to perform any task along with what it is supposed to do. Although it is not advisable to make "+" perform subtraction or to ask "==" to do any task other than equality comparison, but Operator Overloading can make it possible.
Operator overloading is the ability to tell the compiler how to perform a certain operation when its corresponding operator is used on one or more variables. For example, the compiler acts differently with regards to the subtraction operator “-“ depending on how the operator is being used. When it is placed on the left of a numeric value such as -48, the compiler considers the number a negative value. When used between two integral values, such as 80-712, the compiler applies the subtraction operation. When used between an integer and a double-precision number, such as 558-9.27, the compiler subtracts the left number from the right number; the operation produces a double-precision number. When the - symbol is doubled and placed on one side of a variable, such as --Variable or Variable--, the value of the variable needs to be decremented; in other words, the value 1 shall be subtracted from it. All of these operations work because the subtraction operator “-” has been reconfigured in various classes to act appropriately.
0 comments:
Post a Comment