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
E0308
Compilation 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
x
andy
have the return value of the first functionbig(int x, int y)
- Variable
z
has 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.