what do you understand by default arguments and constant arguments in C++? write a short note on their usefulness
Answers
Default Arguments in C++
A default argument is a value provided in function declaration that is automatically assigned by the compiler if caller of the function doesn’t provide a value for the argument with default value.
Following is a simple C++ example to demonstrate use of default arguments. We don’t have to write 3 sum functions, only one function works by using default values for 3rd and 4th arguments.
#include<iostream>
using namespace std;
// A function with default arguments, it can be called with
// 2 arguments or 3 arguments or 4 arguments.
int sum(int x, int y, int z=0, int w=0)
{
return (x + y + z + w);
}
/* Drier program to test above function*/
int main()
{
cout << sum(10, 15) << endl;
cout << sum(10, 15, 25) << endl;
cout << sum(10, 15, 25, 30) << endl;
return 0;
}
Output:
25
50
80
Key Points:
Default arguments are different from constant arguments as constant arguments can’t be changed whereas default arguments can be overwritten if required.
Default arguments are overwritten when calling function provides values for them. For example, calling of function sum(10, 15, 25, 30) overwrites the value of z and w to 25 and 30 respectively.
Default arguments: C++ allows us to assign default values to a function’s parameters which are useful in case a matching argument is not passed in the function call statement. The default values are specified at the time of function declaration.
Example: float interest(float principal, int time, float rate=0.10);
Constant argument: By constant argument, it is meant that the function cannot modify these arguments. In order to make an argument constant to a function, we can use the keyword const as shown : int sum (const int a, const int b); The qualifier const in function prototype tells the compiler that the function should not modify the argument. The constant arguments are useful when functions are called by reference.