FAQ 23.02 When should operator overloading be used?

When it makes sense to users.

The goal of operator overloading should be to improve the readability of code that uses a class. However, it should be used only in ways that are semantically familiar to users. For instance, it would be nonintuitive to use operator+ for subtraction.

The ultimate goal is to reduce both the learning curve and the defect rate for users of a class. Another related goal is to enable users to program in the language of the problem domain rather than in the language of the machine.

Here are a few examples of operator overloading that are intuitive.

  • myString + yourString might concatenate two string objects.

  • myDate++ might increment a Date object.

  • a * b might multiply two Number objects.

  • a[i] might access an element of an Array object.

  • x = *p might dereference a "smart pointer" (see FAQ 31.09) that acts as if it points to a disk record. The actual implementation could use a database lookup to get the value of record x.

While it is true that operator overloading can be overutilized (by trying to define everything as an operator), it can also be underutilized. For some reason, some developers hate to implement overloaded operators in their classes. They don't do it even in places where it should be done. One reason some developers don't do it is because they're not used to it they don't do it every day, so they're not comfortable with it. Another reason they don't do it is because Java doesn't have operator overloading (as if that were a reason to not do something in C++). And another reason they don't do it is because they think that it makes their code ugly by adding all those member functions with funny operator names.

Our response to these concerns (in particular the last one) is go back to two of the central tenets of this book: "Design classes from the outside in" and "Think of your users, not yourself" when designing interfaces. In particular, if overload operators make sense to the users of the library/class or their code will be easier to understand and maintain, then the developer should define overloaded operators.



C++ FAQs
C Programming FAQs: Frequently Asked Questions
ISBN: 0201845199
EAN: 2147483647
Year: 2005
Pages: 566
Authors: Steve Summit

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net