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.
string val = {}instead ofstring val = "". The former uses the default constructor, whereas the latter uses an implicit constructor to create a string from aconst char*. The former might be more efficient. In particular, it is declared with noexcept.