chapter four

4 Class Operations

 

This chapter covers

  • Choosing between operators and methods
  • Handling self-assignment and return value optimization
  • Cooperating with the compiler for class members
  • Deciding between explicit and implicit conversions
  • Prefix and postfix versions of increment and decrement operators

This chapter continues the discussion of using instances well. The concept of the class invariant is always in view, but these mistakes need to be addressed with a different focus than the previous chapters. This certainly does not mean that it is less important, only that the emphasis is broader, touching on areas that do not necessarily directly affect the state of an object.

The category of performance is frequently addressed in these mistakes. Several issues emphasize this aspect by focusing on eliminating unnecessary temporary objects. These temporary objects occur when an intermediate step in an expression evaluation requires an intermediary object to hold the results of a partial evaluation, which will be used in further evaluation. Knowing when these temporaries are created and how to design a class to eliminate many of them significantly affects the number of constructor and destructor calls that occur.

Other issues focus on misusing operators that affect common usage or performance. C++ provides a significant amount of flexibility for the developer, and this flexibility must be respected to avoid improper usage of features.

4.1 Mistake #18 Misunderstanding Variable Shadowing

4.2 Mistake #19 Allowing Duplication of Unique Objects

4.3 Mistake #20 Not Coding for Return Value Optimization

4.4 Mistake #21 Not Returning a Reference from Assignment Operators

4.5 Mistake #22 Forgetting to Handle Self-assignment

4.6 Mistake #23 Misunderstanding Prefix and Postfix Forms

4.7 Mistake #24 Misleading Implicit Conversion Operators

4.8 Mistake #25 Overusing Implicit Conversion Constructors

4.9 Mistake #26 Focusing Too Much on Standalone Operators

4.10 Mistake #27 Failing to Mark Non-mutating Methods Constant

4.11 Mistake #28 Not Properly Marking Class Methods Static

4.12 Mistake #29 Incorrectly Choosing Between Member and Non-member Functions

4.13 Mistake #30 Wrongly Returning Strings from Accessor Methods