Default arguments in C++In a function, arguments are defined as the values passed when a function is called. Values passed are the source, and the receiving function is the destination. Now let us understand the concept of default arguments in detail. Definition A default argument is a value in the function declaration automatically assigned by the compiler if the calling function does not pass any value to that argument. Characteristics for defining the default arguments Following are the rules of declaring default arguments -
Example
Code Output 25 50 80 Explanation In the above program, we have called the sum function three times.
Note If the function is overloaded with different data types that also contain the default arguments, it may result in an ambiguous match, which results in an error.Example Output prog.cpp: In function 'int main()': prog.cpp:15:20: error: call of overloaded 'sum(int, int)' is ambiguous cout << sum(10, 15) << endl; // x = 10, y = 15, z = 0, w = 0 ^ prog.cpp:4:5: note: candidate: int sum(int, int, int, int) int sum(int x, int y, int z=0, int w=0) // Here there are two values in the default arguments ^ prog.cpp:9:5: note: candidate: int sum(int, int, float, float) int sum(int x, int y, float z=0, float w=0) // Here sum is overloaded with two float parameter values Explanation Here when we call the sum function with all the parameters(x, y, z, w) or either any one parameter value of z or w, the compiler gets confused about which function to execute. Thus, it creates an ambiguity which results in the error.
Next TopicDynamic binding in C++
|