Default Arguments in C++

C++ allows us to call a function without specifying all its arguments. The function assigns a default values to the parameters which does not have a matching argument in the function call. Default Arguments in C++ are checked for data type at the time of declaration and evaluated at the time of call. In this case only Default Arguments in C++ can have default values and we must add defaults from right to left, we can’t provide a default value to a particular argument in the middle of an argument list.

#include<iostream.h>
#include<conio.h>
using namespace std;
int main()
{
 float amount;
 float value(float p, int n, float r=0.15);
void printline(char ch='*', int l=50);
printline();
amount=value(75000.500, 6);
cout<<"Final value="<<amount<<endl;
amount=value(12000.750, 7,0.50);
cout<<"Final value="<<amount<<endl;
printline('*');
getch();
return 0;
}
float value(float p, int n, flaot r)
{
 int y=1;
float sum=p;
while(y<=n)
{
 sum=sum*(1+r);
 y=y+1;
}
return(sum);
}
void printline(char ch, int l)
{
 for(int i=1;i<=l;i++)
 printf("%c",ch);
printf("\n");
}

Default Arguments are very useful in situations where some arguments always have the same value. It also provides greater flexibility to the programmers. A function can be written with more parameters than we required for its most common application. Using default arguments, a programmer can use only those arguments that are meaningful to a particular situation.