|
|
|
|
|
|
|
Analysis: The implementation of operator++, on lines 2529, has been changed to dereference the this pointer and to return the current object. This provides a Counter object to be assigned to a. If the Counter object allocated memory, it would be important to override the copy constructor. In this case, the default copy constructor works fine. |
|
|
|
|
|
|
|
|
Note that the value returned is a Counter reference, thereby avoiding the creation of an extra temporary object. It is a const reference because the value should not be changed by the function using this Counter. |
|
|
|
|
|
|
|
|
Overloading the Postfix Operator |
|
|
|
|
|
|
|
|
What if you want to overload the postfix increment operator? Here the compiler has a problem. How is it to differentiate between prefix and postfix? By convention, an integer variable is supplied as a parameter to the operator declaration. The parameter's value is ignored; it is just a signal that this is the postfix operator. |
|
|
|
|
|
|
|
|
The Difference Between Prefix and Postfix |
|
|
|
|
|
|
|
|
Before you can write the postfix operator, you must understand how it is different from the prefix operator. To review, prefix says increment and then fetch while postfix says fetch and then increment. |
|
|
|
|
|
|
|
|
Therefore, while the prefix operator can simply increment the value and then return the object itself, the postfix must return the value that existed before it was incremented. To do this, you must create a temporary object, after all. This temporary will hold the original value while you increment the value of the original object. You return the temporary, however, because the postfix operator asks for the original value, not the incremented value. |
|
|
|
|
|
|
|
|
Let's go over that again. If you write |
|
|
|
|
|
|
|
|
If x is 5, after this statement a is 5, but x is 6. I return the value in x and assign it to a, and then increase the value of x. If x is an object, its postfix increment operator must stash away the original value (5) in a temporary object, increment x's value to 6, and then return that temporary to assign its value to a. |
|
|
|
|
|
|
|
|
Note that because the temporary is being returned, it must be returned by value and not by reference, because the temporary will go out of scope as soon as the function returns. |
|
|
|
|
|
|
|
|
Listing 14.3 demonstrates the use of both the prefix and the postfix operators. |
|
|
|
|
|