1

I am trying to pass an std::string as a default argument to a function.

I'm trying like follows

void string_fun(int i, string val = "", int j = 10)
// void string_fun(int i, string val, int j = 10) // <-- error since no default value
{
    cout << "values " << endl;
    cout << "i: " << i << endl;
    cout << "val: " << val << endl;
    cout << "j: " << j << endl;
}

void ret_fun()
{
    string fun;
    cout << "values " << endl;
    cout << "fun: " << fun << endl;
}

int main()
{
    string_fun(3);
    ret_fun();
    return 0;
}

I heard that the default constructor of a string will initialize the string, if that is correct what will be the value of that? See here if I'm using only string val as the argument to the function, I'll get compilation error. But when I print the string both val and fun I'm getting the same output. My question is what make the two string different in case of their values, since string val = "" also creates a blank string.

1
  • 1
    Consider using string val = {} instead of string val = "". The former uses the default constructor, whereas the latter uses an implicit constructor to create a string from a const char*. The former might be more efficient. In particular, it is declared with noexcept. Commented Apr 30, 2014 at 18:11

1 Answer 1

3

You are looking at an argument list for a function, the rules are therefore different. It doesn't matter that std::string has a default constructor.

The point is that the language's rules for argument lists make sure that you allow or disallow a caller to omit parameters from the call. When a default value is given, the caller may omit the parameter and the default values is used instead. Without a default value, the caller must supply an appropriate parameter.

If you leave out the default value of the second parameter, your call

string_fun(3);

does not compile as it requires at least two parameters. You could even use the default constructor in the call:

string_fun(3, string());
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.