postfix and prefix operator overloading question
Usually, postfix and prefix operator overloading is defined as follows,
Code:
class Number {
public:
Number& operator++ (); // prefix ++
Number operator++ (int); // postfix ++
};
My question is that why prefix returns by value and postfix returns by reference?
Re: postfix and prefix operator overloading question
Quote:
Originally Posted by LarryChen
My question is that why prefix returns by value and postfix returns by reference?
You actually mean to ask why the prefix version returns by reference and the postfix version returns by value. We normally expect the prefix version to return the updated value, hence it would typically return *this; Therefore, there is no point in returning by value when you do not need a copy. But we normally expect the postfix version to return the previous value, hence it is sensible to return a copy of the object before the increment.
Re: postfix and prefix operator overloading question
The postfix ++ does not return a reference because it will be invalid, example for build-in int operator++ :
++x; // returns x+1
x++; /* create a copy let's say tmp = x; then x = x + 1; and finally return the tmp value, a tmp reference will be invalid */
This is the reason why: ++var is more efficient then var++, no copy and no temporary variable.