DekGenius.com
Team LiB   Previous Section   Next Section

12.2 Creating Useful Operators

Operator overloading can make your code more intuitive and enable it to act more like the built-in types. However, if you break the common idiom for the use of operators, operator overloading can make your code unmanageably complex and obtuse. Therefore you should always resist the temptation to use operators in new and idiosyncratic ways.

For example, although it might be tempting to overload the increment operator (++) on an employee class to invoke a method incrementing the employee's pay level, this can create tremendous confusion for clients of your class. The increment operator normally means "increase this scalar value by one." Giving it the new meaning of "increase this employee's pay level" will be obvious to the person implementing the operator, but may be very confusing to future clients of the class. It is best to use operator overloading sparingly and only when its meaning is clear and consistent with how the built-in classes operate.

    Team LiB   Previous Section   Next Section