Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between variable-length argument and function overloading

This C++ question seems to be pretty basic and general but still I want someone to answer.

1) What is the difference between a function with variable-length argument and an overloaded function? 2) Will we have problems if we have a function with variable-length argument and another same name function with similar arguments?

like image 483
raj_arni Avatar asked Dec 18 '25 00:12

raj_arni


1 Answers

2) Do you mean the following?

int mul(int a, int b);
int mul(int n, ...);

Let's assume the first multiplies 2 integers. The second multiplies n integers passed by var-args. Called with f(1, 2) will not be ambiguous, because an argument passed through "the ellipsis" is associated with the highest possible cost. Passing an argument to a parameter of the same type however is associated with the lowest possible cost. So this very call will surely be resolved to the first function :)


Notice that overload resolution only compares argument to parameter conversions for the same position. It will fail hard if either function for some parameter pair has a winner. For example

int mul(int a, int b);
int mul(double a, ...);

Imagine the first multiplies two integers, and the second multiplies a list of doubles that is terminated by a 0.0. This overload set is flawed and will be ambiguous when called by

mul(3.14, 0.0); 

This is because the second function wins for the first argument, but the first function wins for the second argument. It doesn't matter that the conversion cost for the second argument is higher for the second function than the cost of the first argument for the first function. Once such a "cross" winner situation is determined, the call for such two candidates is ambiguous.

like image 179
Johannes Schaub - litb Avatar answered Dec 19 '25 13:12

Johannes Schaub - litb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!