12: ~Counter(){}
13: int GetItsVal()const { return itsVal; }
14: void SetItsVal(int x) {itsVal = x; }
15: private:
16: int itsVal;
17: };
18:
19: Counter::Counter():
20: itsVal(0)
21: {}
22:
23: Counter::Counter(int val):
24: itsVal(val)
25: {}
26:
27: int main()
28: {
29: int theInt = 5;
30: Counter theCtr = theInt;
31: cout << “theCtr: “ << theCtr.GetItsVal() << endl;
32: return 0;
33: }
theCtr: 5
The important change is on line 11, where the constructor is overloaded to take
an int, and on lines 23–25, where the constructor is implemented. The effect of
this constructor is to create a Counterout of an int.
Given this, the compiler is able to call the constructor that takes an intas its argument.
Here’s how:
Step 1: Create a Countercalled theCtr.
This is like saying int x = 5;which creates an integer variable xand then initializes it
with the value 5. In this case, a Counterobject theCtris being created and initialized
with the integer variable theInt.
Step 2: Assign to theCtrthe value of theInt.
But theIntis an integer, not a counter! First, you have to convert it into a Counter. The
compiler will try to make certain conversions for you automatically, but you have to
teach it how. You teach the compiler how to make the conversion by creating a construc-
tor. In this case, you need a constructor for Counterthat takes an integer as its only
parameter:
OUTPUT
322 Day 10
LISTING10.17 continued
ANALYSIS