I was trying out default argument values and function overloading in c++ by compiling the following code and I was surprised by the output which was :
Line 19: error: call of overloaded 'add()' is ambiguous
The code I compiled is :
#include <iostream>
using namespace std;
void add(int a=1, int b=1){
cout<<a+b;
}
void add(){
int a =2, b=2;
cout<<a+b;
}
int main(){
add();
return 0;
}
Any explanations why it is ambiguous? Thx in advance.
Because both signatures match the call.
can be interpreted as either
add(1,1)oradd(). When you writevoid add(int a=1, int b=1), you’re telling the compiler – “Listen dude, if I calladdwith no parameters, I want you to default them to1“Most importantly, what do YOU expect to happen when you call
add()with no parameters?If you expect it to print
2, remove the version that takes no parameters.If you expect it to print
4, remove the default parameters from the first version.