[   ^ to index...   |   <-- previous   ]

Default arguments

For convenience, C++ allows you to define a "default argument" for any formal parameter in any function or method. If you omit one of the arguments, it will be supplied:

void cat(int a = 5); // declaration with default arg cat(); // equivalent to cat(5);

For reasons of code sanity, C++ requires that you provide default arguments for all parameters after the first for which you provide a default argument. Otherwise, it would be easy to introduce ambiguities and confusing code:

void hat(int a = 1, double c = 4.0, double e, int d); hat(2, 3.0, 5); // What gets called?

Overloading with default args

Default arguments and overloading rules have some "interesting" feature interactions.

Which of the following foo method gets called for each invocation? Can all definitions coexist? Are all calls legal? (Assume legal statements/definitions occur in order.)

// Definitions int foo(char x, char y = 'a'); // 1 void foo(int x); // 2 double foo(int x); // 3 int foo(char x); // 4 // Invocations foo('a', 'b'); double x = foo(foo('b')); double y = foo(foo('b', 'b'));

Click here for sample code...


Last modified: Mon Jul 24 22:30:43 PDT 2000