Working with Advanced Functions 325
10
Summary ..............................................................................................................
Today, you learned how to overload member functions of your classes. You also learned
how to supply default values to functions and how to decide when to use default values
and when to overload.
Overloading class constructors enables you to create flexible classes that can be created
from other objects. Initialization of objects happens at the initialization stage of construc-
tion and is more efficient than assigning values in the body of the constructor.
The copy constructor and the assignment 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 can allocate memory for the target member variable.
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.
thisrefers to the current object and is an invisible parameter to all member functions.
The dereferenced thispointer is often returned by overloaded operators so that they can
participate in expressions.
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 I ever use default values when I can overload a function?
A It is easier to maintain one function than two, and it is often easier to understand a
function with default parameters than to study the bodies of two functions.
Furthermore, updating one of the functions and neglecting to update the second is a
common source of bugs.
Q Given the problems with overloaded functions, why not always use default val-
ues instead?
A Overloaded functions supply capabilities not available with default variables, such
as varying the list of parameters by type rather than just by number or providing a
different implementation for different parameter type combinations.