
Default Function Arguments
C++ allows us to call a function without specifying all its arguments. In such cases, the function assigns a default value to the parameter which does not have a matching argument in the function call. Default values are specified when the function is declared. The compiler looks at the prototype to see how many arguments a function uses and alerts the program for possible default values.
Here is an example of a prototype ( i.e. function declaration ) with default values :
void myfunc ( int a = 5, double b = 12 . 5 ) ;
The default value is specified in a manner syntactically similar to a variable initialization. The C++ compiler substitutes the default values if you omit the arguments when you call the function.
You can call the function by using any of the following ways:
myfunc ( 12 , 3 . 65 ) ; // overrides both defaults
myfunc ( 3 ) ; // effectively myfunc ( 3 , 12 . 5 ) ;
myfunc ( ) ; // effectively myfunc ( 5 , 12 . 5 ) ;
To omit the first parameter in these examples, you must omit the second one; however, you can omit the second parameter by itself. This rule applies to any number of parameters. You cannot omit a parameter unless you omit the parameters to its right.