Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.

Share this Page URL
Help

Functions and Operators > Avoid overloading &&, ||, or , (comma) - Pg. 52

52 C++ Coding Standards 30. Avoid overloading &&, ||, or , (comma) . Summary Wisdom means knowing when to refrain: The built-in &&, ||, and , (comma) enjoy special treatment from the compiler. If you overload them, they become ordinary func- tions with very different semantics (you will violate Items 26 and 31), and this is a sure way to introduce subtle bugs and fragilities. Don't overload these operators naïvely. Discussion The primary reason not to overload operator&&, operator||, or operator, (comma) is that you cannot implement the full semantics of the built-in operators in these three cases, and programmers commonly expect those semantics. In particular, the built-in versions evaluate left-to-right, and for && and || also use short-circuit evaluation. The built-in versions of && and || first evaluate their left-hand expression, and if that fully determines the result (false for &&, true for ||) then the right-hand expression doesn't need to be evaluated--and is guaranteed not to be. We all get so used to this handy feature that we routinely allow the correctness of the right-hand side depend