1

what is the reason of having to put that const on the last parameter of my function(it has default argument declaration) if it was not default, it would not need that const

string make_plural(string &word, size_t c, const string &ending = "s")
  {
     return c > 1 ? word + ending : word;
  }

the error is : 'default argument' : cannot convert from 'const char [2]' to 'std::string &'

but i cannot understand why. can any body explain please.

Community
  • 1
  • 1
saeed abbasi
  • 83
  • 10

1 Answers1

1

I have found out the answer myself. we have to put that const because string literals are const and in the code we were initializing a const string to a plain reference which is in error. to make it clear look below:

string &r="some string";

is in error but

const string &r="some string";

is valid and if :

string make_plural(string &word, size_t c,const string &ending = "s")
 {
    return c > 1 ? word + ending : word;

 }

if the first parameter was a plain reference then the call could be:

string str = "thing";
cout << make_plural(str,2) << endl;

but if you want the call to be:

cout << make_plural("thing",2) << endl;

you have to add const for the first parameter as follows

string make_plural(const string &word, size_t cnt,const string &ending = "s")
 {
     return cnt > 1 ? word + ending : word;

 }

reasons and rules to initializing parameter are the same as variables so: plain references cannot be initialized by const values such as a string literals that are consts.

saeed abbasi
  • 83
  • 10
  • I'm not sure the issue is that the string literal is const, because constructing a `std::string` from a string literal will take a copy of the contents anyway. The issue is that a temporary `std::string` is constructed which is an R-value, and you cannot bind a non-const L-value reference to an R-value. – Sean Burton Mar 30 '22 at 11:43