computer science II
c m s c 214  
f a l l   2 0 0 1  

Operator++/--

++ and -- operators were written for convenience, and yet they can be a pain. In particular, it's very difficult to explain how postfix increment and decrement work to a person seeing it for the first time.

What's worse, few C++ books like to cover the topic, because it gets into the messiness of explaining how to implement prefix vs. postfix operators.

Prototypes for operator++/--

According to Stroustrup, the operators should be defined with the following prototypes (as it would appear in :
class Foo {
 public:
   Foo & operator++();      // prefix
   Foo operator++( int );   // postfix
   Foo & operator--();      // prefix
   Foo operator--( int );   // postfix
};
Several things are unusual. First, in order for the compiler to know which code to run (prefix or postfix), the operators have to have different parameters. It was somewhat arbitrarily decided that operator++ without parameters is prefix increment, and the operator++ with a single int parameters is postfix increment. The int is never used. It's only there to distinguish between the two kinds of operators.

The second difference is the postfix operator returns by value, while the prefix operator returns by reference.

Why the difference?

One reason for using ++ is to treat it like a pointer. Think about an Iterator class. An object is basically a pointer.

For prefix increment, you merely have to move the pointer forward and return * this. After all, the iterator points to the correct spot.

With the postfix increment, it's not entirely clear you should return a reference. When you implement the postfix operator, you must actually return the current value, and advance the iterator. But how can this be done?

One simple way is to declare a local variable, and copy the current object. Then, "increment" the data member. Then, return the copy. However, if you do this, then you can't return a reference (returning a reference to a local variable is bad, since that local variable disappears after going out of scope).

Another possibility is to use the "real" postfix ++ operator. For example, if you had a pointer to an element in an array, you might be able to return *ptr++ by reference. However, this assume you have an underlying ++ operator to work with, and assumes that the postfix occurs late enough.

What does STL do? It basically opts for returning the Iterator back by value for postfix operations.

So, how do I do the postfix again?

The main drawback of this method is that you can't apply the postfix operator twice within the same statement (as in (p++)++). Think about why that will produce incorrect results. (You can do it twice using prefix operators, however).

Web Accessibility