Default arguments in C++ and its constraints

Default arguments in C++ and its constraints

Default Arguments:  The values given to the arguments of the function may be defaulted by supplying the variables with default values at the time of declaring a function.  If the function is invoked without specifying the argument’s value, the default value is assumed for the variable.  Thus, default arguments prove useful in C++ for applications where default values for values may be considered, as for pie (p), default value is 3.14, that may be supplied at the time of declaring the function as follows:

float volume(float r, float h, float pie=3.14);

After default value is supplied to the argument pie, the following funtion invocation statement will work-

float result;
result = volume(3.5,4.5);

such that r receives 3.5, h receives 4.5 and the variable pie receives the default value given in prototype i.e. 3.14.

The constraint for the default arguments is that argument can only be defaulted from right to left.  Thus, the following function declaration with default argument results in an error:

float volume(float r, float pie=3.14, float h);

Default arguments are useful in situations where default values must be supplied automatically with writing them explicitly.