Explain Default arguments, Const arguments With Example and Programming.
Default arguments: -
In c++
default arguments are used to call a function without specifying all of its
arguments. In the function prototype declaration the default values are given.
Whenever a call is made to a function without specifying an arguments, the
complier will automatically assign values to the parameters from the default
function prototype declaration. A default argument can in the function
prototype. Once it is defined, it cannot be redefined at function definition
argument list .
Some points
regarding default arguments;
1)
A default argument is checked at the time of
declaration and evaluated at the time of call.
2)
Default argument is used only when any argument
value is missing at function call.
3)
We must add the default parameters from right to
left.
4)
We cannot provide a default parameter in the middle
of an argument list
5)
Default arguments are useful where some arguments
always have the same value
For example: float amount (float principle, int period,
float rate = 0.15);
Note: - principle, period are general formal parameters, rate is Default
argument.
For ex: the
function call
Value= amount (5000, 7); // one argument missing hence
default value will be taken.
The above function call
passes
5000 principle
7 periods
Then the function use the default value
for rate parameter as 0.15 rates.
e.g. void sum( int , int x=10, int y=20); // function prototype with default argument
list.
void main()
{ int a=5,b=15,c=5;
sum(b); //
if we call the function like sum(a,b,c) then there is no use of default
arguments.
-------------
}
void sum( int a1, int a2, int a3) //function declaration
{ int
temp;
temp =
a1+ a2+a3; // a2=10 a3=20 by default arguments. I.e temp=45
}
Const arguments :-
1) Here we
declare the arguments as constants by using “ const “ keyword, in the function definition.
2) The
arguments declared as const cannot be changed in side the function definition.
3) During
calling of the function the const arguments would acquire the values initially
given in the call.
4) Syntax
:- return-type function-name ( const argument, …. ) {
function definition code }
5) Example :-
main(
)
{ void get(int, const int);
add(
5 , 5 ) ;
getch(); }
void add ( int a , const int b )
{
a=10;
// can be reinitialized because it is a simple variable.
b=20 ; //
Not allowed as its declared const
cout << ( a + b ) ; // output 15
}