|
|
|
|
|
|
|
On line 6, 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 1012, the dimensions length, height, and width are initialized, and they are passed to the AreaCube() function on line 15. The values are computed, and the result is printed on line 16. |
|
|
|
|
|
|
|
|
Execution returns to line 18, 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 returns to line 21, and this time neither the width nor the height is passed in. Execution branches for a third time to line 27. The default values are used. The area is computed and then printed. |
|
|
|
|
|
|
|
|
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 different parameter lists. The first and second versions differ 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, as long as the parameter list is different. You can't overload just on return type, however. |
|
|
|
|
|
|
|
|
Function overloading is also called function polymorphism. Poly means many, and morph means form: a polymorphic function is many-formed. |
|
|
|
|
|
|
|
|
Function polymorphism refers to the capability to overload a function with more than one meaning. By changing the number or type of the parameters, you can give two or more functions the same function name, and the right one will be called by matching the parameters used. This enables you to create a function that can average integers, doubles, and other values without having to create individual names for each function, such as AverageInts(), AverageDoubles(), and so on. |
|
|
|
|
|