Sams Teach Yourself C in 21 Days

(singke) #1
Although this seems to show two different ways to call a rectangle function, it is not.
Trying to overload the rectangle function with the above two declarations will generate
an error. Although the parameters being passed seem to be different—a point is being
passed instead of the width and length—, the compiler won’t see these as different.
Rather, the compiler will see two calls to rectangle that both have four arguments that are
all type intvalues.
If you change the second declaration to
int rectangle( int topleftx, int toplefty, long bottomrightx, long
bottomright y );
the compiler will then be able to tell the difference between the two. One will receive
long values— the other, integers. Additionally, the following is another rectangle func-
tion that can also be defined:
int rectangle( int topleftx, int toplefty );
This function is different from the others because it only has two parameters. This is
enough to enable the compiler to differentiate it from the others. You do, however, need
to be cautious with this third function, as you’ll see in the next section.

Creating Default Function Parameter Values ................................................


In addition to being able to overload functions, you can also set default values for func-
tion parameters. This allows a function to adapt if a parameter is omitted. It also enables
you to set up some values, even if the user didn’t supply them. Consider the rectangle
example presented in Listing B2.5.

LISTINGB2.5 rect.cpp. Using default values for function parameters
1: //Using default parameters
2: #include <iostream.h>
3:
4: // Function prototype with default parameters
5: void rectangle (int width = 3, int length = 3, char draw_char = ‘X’);
6:
7: int main(int argc, char* argv[])
8: {
9: cout << “\nrectangle( 8, 2, \’*\’ );\n”;
10: rectangle( 8, 2, ‘*’ );
11:
12: cout << “\nrectangle( 4, 5 );\n”;
13: rectangle( 4, 5 );
14:
15: cout << “\nrectangle( 2 );\n”;
16: rectangle( 2 );

656 Bonus Day 2

37 448201x-Bonus2 8/13/02 11:18 AM Page 656

Free download pdf