< previous page page_219 next page >

Page 219
Listing 14.7 will not compile!

LISTING 14.7 ATTEMPTING TO ASSIGN A COUNTER TO AN INT

d5ef64f4d3250b96ba5c07ca5bbc2f56.gif
 1:     // Listing 14.7
 2:     // This code won't compile!
 3:
 4:     #include <iostream.h>
 5:
 6:     class Counter
 7:     {
 8:     public:
 9:       Counter();
10:       ~Counter(){}
11:       int GetItsVal()const { return itsVal; }
12:       void SetItsVal(int x) {itsVal = x; }
13:     private:
14:       int itsVal;
15:
16:     };
17:
18:     Counter::Counter():
19:     itsVal(0)
20:     {}
21:
22:     int main()
23:     {
24:        int theShort = 5;
25:        Counter theCtr = theShort;
26:        cout << theCtr:  << theCtr.GetItsVal() << endl;
27:         return 0;
28:     }

Output:
Compiler error! Unable to convert int to Counter
Analysis: The Counter class declared on lines 616 has only a default constructor. It declares no particular method for turning an int into a Counter object, so line 25 causes a compile 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 14.8 corrects this by creating a conversion operator: a constructor that takes an int and produces a Counter object.

 
< previous page page_219 next page >

If you like this book, buy it!