error: default argument given for parameter 1

C++FunctionDefault Arguments

C++ Problem Overview


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.

C++ Solutions


Solution 1 - C++

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 - C++

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;
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionpocoaView Question on Stackoverflow
Solution 1 - C++YacobyView Answer on Stackoverflow
Solution 2 - C++e_awuahView Answer on Stackoverflow