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. 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 you or other programmers who have to maintain the code. It is best to use operator overloading sparingly, and only when its meaning is clear and consistent with how the built-in classes operate.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset