33: Counter i;
34: cout << “The value of i is “ << i.GetItsVal() << endl;
35: i.Increment();
36: cout << “The value of i is “ << i.GetItsVal() << endl;
37: ++i;
38: cout << “The value of i is “ << i.GetItsVal() << endl;
39: Counter a = ++i;
40: cout << “The value of a: “ << a.GetItsVal();
41: cout << “ and i: “ << i.GetItsVal() << endl;
42: return 0;
43: }
The value of i is 0
The value of i is 1
The value of i is 2
The value of a: 3 and i: 3
The implementation of operator++, on lines 25–29, has been changed to derefer-
ence the thispointer and to return the current object. This provides a Counter
object to be assigned to a. As discussed, if the Counterobject allocated memory, it
would be important to override the copy constructor. In this case, the default copy con-
structor works fine.
Note that the value returned is a Counterreference, thereby avoiding the creation of an
extra temporary object. It is a constreference because the value should not be changed
by the function using the returned Counter.
The returned Counterobject must be constant. If it were not, it would be possible to per-
form operations on that returned object that might change its values. For example, if the
returned value were not constant, then you might write line 39 as
Counter a = ++++i;
What you should expect from this is for the increment operator (++) to be called on the
result of calling ++i. This would actually result in calling the increment operator on the
object,i, twice—which is something you should most likely block.
Try this: Change the return value to nonconstant in both the declaration and the imple-
mentation (lines 15 and 25), and change line 39 as shown (++++i). Put a break point in
your debugger on line 39 and step in. You will find that you step into the increment oper-
ator twice. The increment is being applied to the (now nonconstant) return value.
It is to prevent this that you declare the return value to be constant. If you change lines
15 and 25 back to constant, and leave line 39 as shown (++++i), the compiler complains
that you can’t call the increment operator on a constant object.
OUTPUT
310 Day 10
LISTING10.11 continued
ANALYSIS