Default Arguments
C++ allows a function to assign default values to
parameters. The default value is assigned when no argument
corresponding to that parameter is specified in the call to
that function.
A function that assigns default arguments is illustrated in
the following code segment:
int add(int iNum1 = 10, int iNum2 = 20)
{
return iNum1 + iNum2;
}
In the above code segment, if the add() function is invoked
without arguments, then the default values of 10 and 20 are
assigned to iNum1 and iNum2, repectively. If values are
passed to the function, then corresponding values are
assigned to iNum1 and iNum2.
The following program illustrates the use of default
arguments:
//Program 7.7
//This program illustrates the use of default arguments
#include<iostream.h>
void add(int iNum1 = 10, int iNum2 = 20)
{
cout<<"Sum is "<<iNum1+iNum2<<endl;
}
void main()
{
int var1 = 5, var2 = 7;
add();
add(var1, var2);
}
The output of Program 7.7 is:
Sum is 30
Sum is 12 |