Sams Teach Yourself C++ in 21 Days

(singke) #1
On line 5, the AreaCube()prototype specifies that the AreaCube()function takes
three integer parameters. The last two have default values.
This function computes the area of the cube whose dimensions are passed in. If no width
is passed in, a width of 25 is used and a height of 1 is used. If the width but not the
height is passed in, a height of 1 is used. It is not possible to pass in the height without
passing in a width.
On lines 9–11, the dimension’s length, height, and width are initialized, and they are
passed to the AreaCube()function on line 14. The values are computed, and the result is
printed on line 15.
Execution continues to line 17, where AreaCube()is called again, but with no value for
height. The default value is used, and again the dimensions are computed and printed.
Execution then continues to line 20, and this time neither the width nor the height is
passed in. With this call to AreaCube(), execution branches for a third time to line 25.
The default values are used and the area is computed. Control returns to the main()func-
tion where the final value is then printed.

118 Day 5


ANALYSIS

DOremember that function parameters
act as local variables within the function.
DOremember that changes to a global
variable in one function change that
variable for all functions.

DON’Ttry to create a default value for a
first parameter if no default value exists
for the second.
DON’Tforget that arguments passed by
value cannot affect the variables in the
calling function.

DO DON’T


Overloading Functions ........................................................................................


C++ enables you to create more than one function with the same name. This is called
function overloading. The functions must differ in their parameter list with a different
type of parameter, a different number of parameters, or both. Here’s an example:
int myFunction (int, int);
int myFunction (long, long);
int myFunction (long);
myFunction()is overloaded with three parameter lists. The first and second versions dif-
fer in the types of the parameters, and the third differs in the number of parameters.
The return types can be the same or different on overloaded functions.
Free download pdf