Learn something new every day
More Info... by email
Operator overloading is a computer programming language feature that allows a programmer to override a default operator. When the operator function is overloaded, it may be declared with custom arguments that are different data types than what the operator was capable of handling by default. The new parameters may be primitive or user defined types. Within the body of the overriding function, a programmer may manipulate the parameter values as desired. By using operator overloading, a programmer can create intuitive shortcuts for manipulating user defined data types or modify how default data types are handled.
When user defined data types are created, there is no way to do simple operational tasks, such as adding two of them together or incrementing internal data by using the unary increment operator with the data type. Operators, including the addition symbol, can be overridden so that if they are used as a binary operators between two custom data types they return a user defined result. In the same way, an unary operator, like the incrementation operator, might be overridden to increase an internal value within the user defined type.
Once an operator is overloaded, the compiler has to make a decision about what to do when it encounters an overloaded operator. The compiler decides the proper action to take based on what data types are being used as operands, or in conjunction with, the operator. If the operands, which are parameter values to the operator function, are user defined data types, the compiler will choose the overloaded function that has parameters which match the operands being used.
Both operator overloading and function overloading in general have been the subject of some debate. Some claim that giving the programmer the freedom of changing the way an operator behaves could introduce the potential for creating unintentional errors by other programmers who use the customized code. The opposing viewpoint proposes that allowing operator overloading gives programmers the capability of creating intuitive and concise code that will be easier to understand, cost less to produce, and reduce errors.