Conversion Operators

What happens when you try to assign a variable of a built-in type, such as int or unsigned short, to an object of a user-defined class? Listing 14.7 brings back the Counter class and attempts to assign a variable of type int to a Counter object.

Listing 14.7 will not compile!

Listing 14.7. Attempting to Assign a Counter to an int
 0: // Listing 14.7 1: // This code won't compile! 2: #include <iostream> 3: 4: class Counter 5: { 6: public: 7: Counter(); 8: ~Counter(){} 9: int GetItsVal()const { return itsVal; } 10: void SetItsVal(int x) {itsVal = x; } 11: private: 12: int itsVal; 13: }; 14: 15: Counter::Counter(): 16: itsVal(0) ...

Get Sams Teach Yourself C++ in 24 Hours, Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.