Date Class Postfix Increment Operator

Overloading the postfix increment operator (defined in Fig. 10.7, lines 49–56) is trickier. To emulate the effect of the postincrement, we must return an unincremented copy of the Date object. For example, if int variable x has the value 7, the statement

cout << x++ << endl;

outputs the original value of variable x. So we’d like our postfix increment operator to operate the same way on a Date object. On entry to operator++, we save the current object (*this) in temp (line 51). Next, we call helpIncrement to increment the current Date object. Then, line 55 returns the unincremented copy of the object previously stored in temp. This function cannot return a reference to the local Date object temp, because a local variable is destroyed when the function in which it’s declared exits. Thus, declaring the return type to this function as Date & would return a reference to an object that no longer exists.


Image Common Programming Error 10.1

Returning a reference (or a pointer) to a local variable is a common error for which most compilers will issue a warning.


..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.119.132.223