Sams Teach Yourself C++ in 21 Days

(singke) #1
Working with Advanced Functions 307

10


36: Counter i;
37: cout << “The value of i is “ << i.GetItsVal() << endl;
38: i.Increment();
39: cout << “The value of i is “ << i.GetItsVal() << endl;
40: ++i;
41: cout << “The value of i is “ << i.GetItsVal() << endl;
42: Counter a = ++i;
43: cout << “The value of a: “ << a.GetItsVal();
44: cout << “ and i: “ << i.GetItsVal() << endl;
45: return 0;
46: }

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
In this version,operator++has been declared on line 15 and is defined on lines
26–32. This version has been declared to return a Counterobject. On line 29, a
temporary variable,temp, is created, and its value is set to match that in the current
object being incremented. When the increment is completed, the temporary variable is
returned. You can see on line 42, that the temporary variable that is returned is immedi-
ately assigned to a.

Returning Nameless Temporaries ..................................................................


There is really no need to name the temporary object created on line 29. If Counterhad
a constructor that took a value, you could simply return the result of that constructor as
the return value of the increment operator. Listing 10.10 illustrates this idea.

LISTING10.10 Returning a Nameless Temporary Object


1: // Listing 10.10 - operator++ returns a nameless temporary object
2:
3: #include <iostream>
4:
5: using namespace std;
6:
7: class Counter
8: {
9: public:
10: Counter();
11: Counter(int val);
12: ~Counter(){}
13: int GetItsVal()const { return itsVal; }

OUTPUT


LISTING10.9 continued


ANALYSIS
Free download pdf