Working with Advanced Functions 321
10
9: public:
10: Counter();
11: ~Counter(){}
12: int GetItsVal()const { return itsVal; }
13: void SetItsVal(int x) {itsVal = x; }
14: private:
15: int itsVal;
16: };
17:
18: Counter::Counter():
19: itsVal(0)
20: {}
21:
22: int main()
23: {
24: int theInt = 5;
25: Counter theCtr = theInt;
26: cout << “theCtr: “ << theCtr.GetItsVal() << endl;
27: return 0;
28: }
Compiler error! Unable to convert int to Counter
The Counterclass declared on lines 7–16 has only a default constructor. It does
not declare methods for turning any built-in types into a Counterobject. In the
main()function, an integer is declared on line 24. This is then assigned to a Counter
object. This line, however, leads to an error. The compiler cannot figure out, unless you
tell it that, given an int, it should assign that value to the member variable itsVal.
Listing 10.17 corrects this by creating a conversion operator: a constructor that takes an
intand produces a Counterobject.
LISTING10.17 Converting intto Counter
1: // Listing 10.17 - Constructor as conversion operator
2:
3: #include <iostream>
4:
5: using namespace std;
6:
7: class Counter
8: {
9: public:
10: Counter();
11: Counter(int val);
OUTPUT
LISTING10.16 continued
ANALYSIS