15: Counter Add(const Counter &);
16:
17: private:
18: int itsVal;
19: };
20:
21: Counter::Counter(int initialValue):
22: itsVal(initialValue)
23: {}
24:
25: Counter::Counter():
26: itsVal(0)
27: {}
28:
29: Counter Counter::Add(const Counter & rhs)
30: {
31: return Counter(itsVal+ rhs.GetItsVal());
32: }
33:
34: int main()
35: {
36: Counter varOne(2), varTwo(4), varThree;
37: varThree = varOne.Add(varTwo);
38: cout << “varOne: “ << varOne.GetItsVal()<< endl;
39: cout << “varTwo: “ << varTwo.GetItsVal() << endl;
40: cout << “varThree: “ << varThree.GetItsVal() << endl;
41:
42: return 0;
43: }
varOne: 2
varTwo: 4
varThree: 6
The Add()function is declared on line 15. It takes a constant Counterreference,
which is the number to add to the current object. It returns a Counterobject,
which is the result to be assigned to the left side of the assignment statement, as shown
on line 37. That is,VarOneis the object,varTwois the parameter to the Add()function,
and the result is assigned to VarThree.
To create varThreewithout having to initialize a value for it, a default constructor is
required. The default constructor initializes itsValto 0 , as shown on lines 25–27.
Because varOneand varTwoneed to be initialized to a nonzero value, another constructor
was created, as shown on lines 21–23. Another solution to this problem is to provide the
default value 0 to the constructor declared on line 11.
The Add()function itself is shown on lines 29–32. It works, but its use is unnatural.
OUTPUT
314 Day 10
LISTING10.13 continued
ANALYSIS