< previous page page_222 next page >

Page 222
LISTING 14.9 continued
d5ef64f4d3250b96ba5c07ca5bbc2f56.gif
35:    Counter ctr(5);
36:    int theShort = ctr;
37:    cout << theShort:  << theShort << endl;
38:    return 0;
39:  }

Output:
theShort: 5
Analysis: On line 14 the conversion operator is declared. Note that it has no return value. The implementation of this function is on lines 2831. Line 30 returns the value of itsVal converted to an int.
Now the compiler knows how to turn ints into Counter objects and vice versa, and they can be assigned to one another freely.
Summary
In this hour you learned about operator overloading.
The copy constructor and operator= are supplied by the compiler if you don't create your own, but they do a member-wise copy of the class. In classes in which member data includes pointers to the free store, these methods must be overridden so that you allocate memory for the target object.
Almost all C++ operators can be overloaded, although you want to be cautious not to create operators whose use is counterintuitive. You cannot change the arity of operators, nor can you invent new operators.
The this pointer refers to the current object and is an invisible parameter to all member functions. The dereferenced this pointer is often returned by overloaded operators.
Conversion operators enable you to create classes that can be used in expressions that expect a different type of object. They are exceptions to the rule that all functions return an explicit value; like constructors and destructors, they have no return type.
Q&A
Q Why would you overload an operator when you can just create a member method?
A It is easier to use overloaded operators when their behavior is well understood. It enables your class to mimic the functionality of the built-in types.

 
< previous page page_222 next page >

If you like this book, buy it!