A default argument is a value provided in a function declaration that is automatically assigned by the compiler if the caller of the function doesn’t provide a value for the argument with a default value.
Following is a simple C++ example to demonstrate the 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.
25 50 80
When Function overloading is done along with default values. Then we need to make sure it will not be ambiguous.
The compiler will throw error if ambiguous. Following is the modified version of above program.
prog.cpp: In function 'int main()': prog.cpp:17:20: error: call of overloaded 'sum(int, int)' is ambiguous cout << sum(10, 15) << endl; ^ prog.cpp:6:5: note: candidate: int sum(int, int, int, int) int sum(int x, int y, int z=0, int w=0) ^ prog.cpp:10:5: note: candidate: int sum(int, int, float, float) int sum(int x, int y, float z=0, float w=0) ^
- 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.
- During calling of function, arguments from calling function to called function are copied from left to right. Therefore, sum(10, 15, 25) will assign 10, 15 and 25 to x, y, and z. Therefore, the default value is used for w only.
- Once default value is used for an argument in function definition, all subsequent arguments to it must have default value. It can also be stated as default arguments are assigned from right to left. For example, the following function definition is invalid as subsequent argument of default variable z is not default.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Templates and Default Arguments
- Some Interesting facts about default arguments in C++
- Default arguments and virtual function
- Command line arguments in C/C++
- When do we pass arguments by reference or pointer?
- Default constructor in Java
- C++ Internals | Default Constructors | Set 1
- Default Methods in C++ with Examples
- Default array values in Java
- Default Assignment Operator and References
- C++ default constructor | Built-in types
- Is body of a Default Constructor blank in C++?
- When does compiler create default and copy constructors in C++?
- Does C++ compiler create default constructor when we write our own?