When default parameters are not specified, function overloading works.
But, why doesn't function overloading work when default parameters are specified?
This program takes two integers and compares them to find the larger of the two.
Then, it compares the maximum value with bigger integers obtained earlier, and the smaller value is output.
Here's the code I written
#include <iostream>
using namespace std;
int big(int a, int b);
int big(int a, int b, int max = 100);
int big(int a, int b) {
if (a > b)
if (a > 100)
{
return 100;
}
else {
return a;
}
else {
if (b > 100) {
return 100;
}
else
{
return b;
}
}
}
int big(int a, int b, int max) {
if (a > b) {
if (a < max) {
return a;
}
else
{
return max;
}
}
else {
if (b < max) {
return b;
}
else {
return max;
}
}
}
int main() {
int x = big(3, 5);
int y = big(300, 60);
int z = big(30, 60, 50);
cout << x << ' ' << y << ' ' << z << endl;
return 0;
}
When I debug the code I wrote, it says
E0308Compilation Error: More than one instance of overloaded function matches the argument list
I learned that function overloading can work when the function parameters are different.
In my code, function names are the same, but function parameters are different:
(int x, int y) and (int x, int y, int max)
But it doesn't work.
In conclusion, why does function overloading not work when default parameters are specified?
IDE that I used:
Microsoft Visual Studio Community 2022 (64-bit) - Current version. 17.5.1
Here's the desire result:
- Variables
xandyhave the return value of the first functionbig(int x, int y) - Variable
zhas the return value of the second functionbig(int x, int y, int max = 100)
This Question is related, but I don't understand how the solution is what I want.
bigfunctions, then name them explicitly:bigandbigWithMaxor something like that. If you need a default parameter, create a separately named stub function that takes less arguments and calls the other function with the hardcoded argument values.int biggest = big(1,2);. There are two equally viable options - theint big(int a, int a)orint big(int a, int b, int max = 100), and the standard gives no criteria to require preferring one form over the other (whichever choice the standard made, it would be "wrong" according to some programmers, and SO would receive questions "why not the other choice?"). Instead, the standard calls this a diagnosable error requiring the programmer to sort things out. To fix: remove the ambiguity - either eliminate the two-argument form entirely or eliminate the default value.