Reputation: 17708
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.
Upvotes: 3
Views: 1635
Reputation: 17708
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?
Upvotes: 0
Reputation: 82171
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.
Upvotes: 8
Reputation: 24351
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.
Upvotes: 17