C++ Default Arguments
C++ language allows us call a function without specifying all its arguments.
In such cases, the function assigns a default value to the parameters which does not have a matching argument in the function call. default
values are specified when function is declared. The compiler look at the prototype to see how many arguments(parameters) in a function use and alerts the program for possible default values. in the below is an example of prototype( function declaration) with default values.
for example:
amount(principal, period, rate=0.15);
|
The default value is specified in manner syntactically similar to a variable initialization.
in the above example prototype declare a default value of 0.15 to the argument rate. A subsequent function call like
passes the value of 5000 to principal variable and 7 to period variable and then lets the function use default value of 0.15 for rate variable. The call
value=amount(5000,5,0.12);
|
passes an explicit value of 0.12 to rate
A default argument or parameters is checked for type at the time of declaration and evaluated at the time of call. one important point here to note is only the trailing arguments can have defualt at the time of
calling. right to left. we can’t provide a default value to a particular argument in the middle of an argument list
Some example below of function declaration with default values are
mul( i, j=5, k=10);
mul(i=5, j);
mul( i=0, j, k=10);
mul( i=2, j=6; k=90);
|
default arguments are useful in conditions where some arguments(parameters) always have the same value. for instance, bank interest may remaining the same for all customers for a particular period of deposit. it also provides a greater flexibility to the programmers.
A function can be written(create) with more parameters than are required for its most common application.
Using default arguments, a programmer can use only those arguments that are meaningful to a particular situation.
<iostream>
using namespace std;
main()
{
amount;
value( p, n, r=0.15);
printline( ch'*', len=40);
printline();
amount=value(5000.00,5)
std::cout <<"\n fincal value="<<amount"<<"\n \n";
printline('=');
0;
}
value( p, n, r)
{
year=1;
sum=p;
(year<=n)
{
sum=sum*(1+r);
year=year+1;
}
(sum);
}
printline(ch, len)
{
( i=1; i<=len; i++)
{
std::cout<<ch;
std::cout<<"\n";
}
|
Advantage of providing the default arguments are
1. we can use default arguments to add new parameters to the existing functions.
2. Default arguments can be used to combine similar function into one
const ARGUMENTS
in c++, an arguments to a function can be declared as const as shown below
The qualifier const tell the compiler that the function(method) should not modify the argument. The compiler will create an error when this condition is violated. This type of declaration is significant only when we passes arguments by reference or pointers