Previous section   Next section

Imperfect C++ Practical Solutions for Real-Life Programming
By Matthew Wilson
Table of Contents
Part Five.  Operators


Chapter 28. Increment Operators

The built-in prefix and postfix increment and decrement operators are great shorthand. Rather than writing



x = x + 1;



we can simply write



++x;



or



x++;



Of greater significance, especially since the advent of the STL, is that these operators can be overloaded for class types. The prefix increment and decrement operators are defined for classes by the following functions:



class X


{


  . . .


  X &operator ++();   // pre-increment


  X &operator —();   // pre-decrement


  X operator ++(int); // post-increment


  X operator —(int); // post-decrement


  . . .



Although there's nothing forcing you to do so, the intent is that the return types of the prefix and postfix forms are as shown above, that is, that the prefix forms return a non-const reference to the current instance, and the postfix forms return a copy of the current instance prior to its value being changed. In other words, they should do as the ints do [Meye1996].

Although it may seem obvious to some, I've seen plenty of people struggle with the implementation of the postfix form, so I'll just show the canonical form:



X X::operator ++(int)


{


  X ret(*this);


  operator ++();


  return ret;


}



Throughout the STLSoft libraries, 18 of the 20 post-increment operators take exactly this form, and, unless you've got a special reason to do something else, this will serve you well.


      Previous section   Next section