26. Preserve natural semantics for overloaded operators

Summary

Programmers hate surprises: Overload operators only for good reason, and preserve natural semantics; if that’s difficult, you might be misusing operator overloading.

Discussion

Although anyone would agree (we hope) that one should not implement subtraction in an operator+ implementation, other cases can be subtle. For example, does your Tensor class’s operator* mean the scalar product or the vector product? Does operator+=( Tensor& t, unsigned u ) add u to each of t’s elements, or will it resize t? In such ambiguous or counterintuitive cases, prefer using named functions instead of fostering cryptic code.

For value types (but not all types; see Item 32): “When in doubt, do as ...

Get C++ Coding Standards: 101 Rules, Guidelines, and Best Practices now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.