< previous page page_220 next page >

Page 220
LISTING 14.8 CONVERTINGintTOCounter

d5ef64f4d3250b96ba5c07ca5bbc2f56.gif
 1:     // Listing 14.8
 2:     // Constructor as conversion operator
 3:
 4:     #include <iostream.h>
 5:
 6:     class Counter
 7:     {
 8:     public:
 9:       Counter();
10:       Counter(int val);
11:       ~Counter(){}
12:       int GetItsVal()const { return itsVal; }
13:       void SetItsVal(int x) {itsVal = x; }
14:    private:
15:       int itsVal;
16:
17:     };
18:
19:     Counter::Counter():
20:     itsVal(0)
21:     {}
22:
23:     Counter::Counter(int val):
24:     itsVal(val)
25:     {}
26:
27:
28:     int main()
29:     {
30:       int theShort = 5;
31:       Counter theCtr = theShort;
32:       cout << theCtr:  << theCtr.GetItsVal() << endl;
33:       return 0;
34:     }

Output:
theCtr: 5
The important change is on line 10, where the constructor is overloaded to take an int, and on lines 2325, where the constructor is implemented. The effect of this constructor is to create a Counter out of an int.
Given this, the compiler is able to call the constructor that takes an int as its argument. What happens, however, if you try to reverse the assignment with the following:
1:   Counter theCtr(5);
2:   int theShort = theCtr;
3:   cout << theShort :  << theShort << endl;

 
< previous page page_220 next page >

If you like this book, buy it!