Sams Teach Yourself C++ in 21 Days

(singke) #1
Working with Advanced Functions 311

10


Overloading the Postfix Operator ..................................................................


So far, you’ve overloaded the prefix 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.

Difference Between Prefix and Postfix ..........................................................


Before you can write the postfix operator, you must understand how it is different from
the prefix operator. You learned about this in detail on Day 4, “Creating Expressions and
Statements” (see Listing 4.3).
To review, prefix says “increment, and then fetch,” but postfix says “fetch, and then
increment.”
Thus, although 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 that will hold the original value, increment
the value of the original object, and then return the temporary object.
Let’s go over that again. Consider the following line of code:
a = x++;
If xwas 5, after this statement ais 5, but xis 6. Thus, the value in xwas returned and
assigned to a, and then the value of xis increased. If xis 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 object to assign its original 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 10.12 demonstrates the use of both the prefix and the postfix operators.

LISTING10.12 Prefix and Postfix Operators


1: // Listing 10.12 - Prefix and Postfix operator overloading
2:
3: #include <iostream>
4:
5: using namespace std;
6:
7: class Counter
8: {
Free download pdf