error: default argument given for parameter 1
109,065
Solution 1
You are probably redefining the default parameter in the implementation of the function. It should only be defined in the function declaration.
//bad (this won't compile)
string Money::asString(bool shortVersion=true){
}
//good (The default parameter is commented out, but you can remove it totally)
string Money::asString(bool shortVersion /*=true*/){
}
//also fine, but maybe less clear as the commented out default parameter is removed
string Money::asString(bool shortVersion){
}
Solution 2
I made a similar error recently. this is how I resolved it.
when having a function prototype and definition. the default parameter is not specified in the definition.
eg:
int addto(int x, int y = 4);
int main(int argc, char** argv) {
int res = addto(5);
}
int addto(int x, int y) {
return x + y;
}
Author by
pocoa
Updated on July 31, 2022Comments
-
pocoa almost 2 years
I'm getting this error message with the code below:
class Money { public: Money(float amount, int moneyType); string asString(bool shortVersion=true); private: float amount; int moneyType; };
First I thought that default parameters are not allowed as a first parameter in C++ but it is allowed.
-
pocoa about 14 yearsNow it says: string Money::asString()' does not match any in class `Money'
-
Yacoby about 14 years@pocoa You still need to keep the
bool shortVersion
parameter, just remove or comment out the= true
-
pocoa about 14 years@Yacoby: Thanks, you were right. It doesn't make any sense, very confusing.
-
sbi about 14 years@pocoa: Actually, it does make sense. If you give default values for parameters, these are filled in at the caller. So they have to be in the function's declaration, because this is what the callers need to see. If you had to repeat them at the definition it would be redundant and more hassle to maintain. (This is also why I disagree with Yacoby about commenting out the default parameters in the implementation. IME, in real projects such comments will be out of sync with the declaration sooner or later.
-
pocoa about 14 yearsWhen the interface and implementations are different from each other, it's making it harder to remember the actual definition. So you need to check the header file every time. Actually I liked the second usage, which comments the default parameter.
-
sbi about 14 yearsThe actual definition is
std::string Money::asString(bool)
. Note that it doesn't even include the parameter's name. And, indeed, you can use different names in the declaration than in the definition. (This is important in huge project when - for whatever reasons - you want to change the name in the definition, but don't want to recompile millions of lines of code which depend on the declaration.)