146

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.

Daniel Walker
  • 6,380
  • 5
  • 22
  • 45
pocoa
  • 4,197
  • 9
  • 37
  • 45

2 Answers2

314

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,159
  • 1
  • 12
  • 17
Yacoby
  • 54,544
  • 15
  • 116
  • 120
  • 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
  • 13
    @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
  • 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
13

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;
}
emma-ea
  • 324
  • 2
  • 5