Default Arguments
In C++ a function can be called 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. The default value is specified when function is declared.
The default value is specified like the variable initialization. The prototype for the declaration of default value of an argument looks like float amount (float p, int time, float rate=0.10);
// declares a default value of 0.10 to the argument rate.
The call of this function as
value = amount (4000,5) ;// one argument missing for rate passes the value 4000 top, 5 to time and the function looks the prototype for missing argument that is declared as default value 0.10 the function uses the default value 0.10 for the third argument. But the call
value = amount (4000,5,0.15);
no argument is missing, in this case function uses this value 0.15 for rate.
Note : only the trailing arguments can have default value. We must add default from right to left. E.g.
int add( int a, int b =9, int c= 10 ); // legal
int add(int a=8, int b, int c); // illegal
int add(int a, int b = 9, int c); //illegal
int add( int a=8, int b=9,int c=10) // legal
Types of default arguments: -
Automatic | External | Static | Register | Mutable | |
Lifetime | Within function | Throughout the program | Throughout program | Within function | Apply only for object |
Visibility | Within function |
Post A Comment:
0 comments so far,add yours