What are default arguments in functions?
- C++ allows a function to assign a parameter a default value when no argument corresponding to that parameter is specified in a call to that function. The default value is specified in a manner syntactically similar to a variable initialization.
- For example, this declares MyFunction as taking one int argument with a default value of 0 :
Void MyFunction(int i =0)
{
//…
//…
}
- Now, this MyFunction() can be called one of the following two ways :
MyFunction(10); //passing explicit value
MyFunction(); //not passing any value; function will give default value
- One of the reasons why default arguments are included in C++ is because they provide another method for the programmer to manager greater complexity.
- To handle the widest variety of situations, quite frequently a function contains more parameters than are required for its most common usage.
- Thus, when the default arguments apply, you need specify only the arguments that are meaningful to the exact situation, not all those needed by the most general case.