Default 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 value are specified when the function is declared. The compiler looks at the prototype to see how many argument a function uses and alert the program for possible default value. Here is an example of a prototype with default values:

float amount (float principle, int period, float rate=0.15);

The default value is specified in a manner syntactically similar to a variable initialization. The above prototype is declare a default value of 0.15 to the argument rate. A subsequent function call like

value = amount (5000,7); // one argument missing
passes the value of 5000 to principle and 7 to period and then lets the function use default value of 0.5 for rate. The call
value = amount (5000,5,0.12); //no missing argument

passes an explicit value of 0.12 to rate.

No comments:

Post a Comment