Listing 10.2 replaces the overloaded DrawShape()function with a single function
with default parameters. The function is declared on line 13 to take three parame-
ters. The first two,aWidthand aHeight, are integers, and the third,UseCurrentVals, is a
boolthat defaults to false.
The implementation for this somewhat awkward function begins on line 29. Remember
that whitespace doesn’t matter in C++, so the function header is actually on lines 29–33.
Within the method, the third parameter,UseCurrentValue, is evaluated on line 38. If it is
true, the member variables itsWidthand itsHeightare used to set the local variables
printWidthand printHeight, respectively.
If UseCurrentValueis false, either because it has defaulted false or was set by the user,
the first two parameters are used for setting printWidthand printHeight.
Note that if UseCurrentValueis true, the values of the other two parameters are com-
pletely ignored.
Choosing Between Default Values and Overloaded Functions ..........................
Listings 10.1 and 10.2 accomplish the same thing, but the overloaded functions in
Listing 10.1 are easier to understand and more natural to use. Also, if a third variation is
needed—perhaps the user wants to supply either the width or the height, but not both—it
is easy to extend the overloaded functions. The default value, however, will quickly
become unusably complex as new variations are added.
How do you decide whether to use function overloading or default values? Here’s a rule
of thumb:
Use function overloading when
- No reasonable default value exists.
- You need different algorithms.
- You need to support different types in your parameter list.
The Default Constructor ......................................................................................
The point of a constructor is to establish the object; for example, the point of a
Rectangleconstructor is to make a valid rectangle object. Before the constructor runs,
no rectangle exists, only an area of memory. After the constructor finishes, there is a
complete, ready-to-use rectangle object. This is a key benefit of object-oriented
294 Day 10
ANALYSIS