106

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.

Wolf
  • 8,482
  • 7
  • 48
  • 92
pocoa
  • 3,749
  • 9
  • 35
  • 44

1 Answers1

240

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){
}
Rptx
  • 1,098
  • 1
  • 12
  • 17
Yacoby
  • 51,022
  • 12
  • 106
  • 116
  • 1
    Now it says: string Money::asString()' does not match any in class `Money' – pocoa Mar 30 '10 at 13:58
  • 1
    @pocoa You still need to keep the `bool shortVersion` parameter, just remove or comment out the `= true` – Yacoby Mar 30 '10 at 14:01
  • @Yacoby: Thanks, you were right. It doesn't make any sense, very confusing. – pocoa Mar 30 '10 at 14:09
  • 11
    @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 Mar 30 '10 at 14:17
  • 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 Mar 30 '10 at 14:21
  • 1
    So C++ is not like Python which works as you expected most of the time. It's a big hassle :) – pocoa Mar 30 '10 at 14:23
  • 2
    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 Mar 30 '10 at 14:26