views:

285

answers:

3

In his The C++ Programming Language Stroustrup gives the following example for inc/dec overloading:

class Ptr_to_T {
 T* p;
 T* array ;
 int size;
public:
 Ptr_to_T(T* p, T* v, int s); // bind to array v of size s, initial value p
 Ptr_to_T(T* p); // bind to single object, initial value p
 Ptr_to_T& operator++(); // prefix
 Ptr_to_T operator++(int); // postfix
 Ptr_to_T& operator--(); // prefix
 Ptr_to_T operator--(int); // postfix
 T&operator*() ; // prefix
}

Why prefix operators return by reference while postfix operators return by value?

Thanks.

+16  A: 

The postfix operator returns a copy of the value before it was incremented, so it pretty much has to return a temporary. The prefix operator does return the current value of the object, so it can return a reference to, well, its current value.

Timo Geusch
combined with the fact that you can't return a temporary by reference, this is a great answer.
xtofl
+7  A: 

To understand better, you have to imagine (or look at) how are these operators implemented. Typically, the prefix operator++ will be written more or less like this:

MyType& operator++()
{
    // do the incrementation
    return *this;
}

Since this has been modified "in-place", we can return a reference to the instance in order to avoid a useless copy.

Now, here's the code for the postfix operator++:

MyType operator++(int)
{
    MyType tmp(*this); // create a copy of 'this'
    ++(*this); // use the prefix operator to perform the increment
    return tmp; // return the temporary
}

As the postfix operator returns a temporary, it has to return it by value (otherwise, you'll get a dangling reference).

The C++ Faq Lite also has a paragraph on the subject.

Luc Touraille
A: 

Suppose I use overloaded preincrement to increment a private member. Doesn't returning a reference to a private member turns the ++private_var expression to an lvalue thus making it possible to modify the private member directly?

Jack
You don't return the reference to private member, but to your class' object. (because the outside world was incrementing your object, not it's private field).
Kasprzol