Differences between Function Overloading and Function with Default Argument(s)
After having discussion on 'Function overloading' and 'Function with default argument' one may think that,
these two are very similar, because in both the occasions functions can be
called with an optional number of arguments. This is true but still they are
not similar.
In
case of function with default argument you may have choice in using number of arguments
while calling a function but still the basic behaviour of the function remains
same. Moreover if you wish to skip the first or middle argument in function
calling, C++ will make no attempt to interpreter that. Let’s consider the following function
prototype to understand this fact more.
float
Amt(float P = 2000, int T = 2, float R = 0.08);
Case 1:
Amt(3);
Suppose here the value 3 you want
to send as value for ‘T’, but it is not possible. C++ will assign it to ‘P’ and
for rest of the arguments default values will be applicable.
Case 2:
Amt(5000,0.13);
Suppose here you want to skip the
middle argument. But C++ will assign 5000 to ‘P’ and 0.13 to ‘T’ and for the
last argument default value will be applied.
Thus
by now I think it has become clear that, with default argument C++ expects that
only the arguments on the right side can be defaulted.
However
you can overcome all of these limitations very easily by overloading Amt() for various possible
combinations of arguments, moreover with function overloading you can make a
function working differently depending upon the different argument
combinations.
But,
with default argument only one instance of function definition is applicable.
No comments:
Post a Comment