views:

361

answers:

1

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.

+4  A: 

You are probably redefining the default parameter in the implementation of the function. It should only be defined in the function definition.

//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){
}
Yacoby
Now it says:string Money::asString()' does not match any in class `Money'
pocoa
@pocoa You still need to keep the `bool shortVersion` parameter, just remove or comment out the `= true`
Yacoby
@Yacoby: Thanks, you were right. It doesn't make any sense, very confusing.
pocoa
@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.
sbi
When 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.
pocoa
So C++ is not like Python which works as you expected most of the time. It's a big hassle :)
pocoa
The 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.)
sbi
Well, it's even worse...
pocoa
@sbi: But I got your point.
pocoa