Reputation: 518
All these lines compile and run, with nothing printed in the output:
std::string ss{6};
ss=7;
std::cout << "ss " << ss << "\n";
I do not see any referenced constructor for std::string
that would suggest it can coerce an integer to a string, so why does the compiler not complain?
Upvotes: 3
Views: 185
Reputation: 18902
The "problem" is that a std::string
is assignable from char
and int
is implicitly convertible to char
.
Take a look at std::basic_string::operator= point (4):
basic_string& operator=( CharT ch );
EDIT
As stated in M.M's comment, std::string ss{6};
calls the constructor taking initializer_list<char>
(see std::basic_string::basic_string
point (9)
)... and the problem resurfaces.
Upvotes: 5
Reputation: 186
The line ss=7
does not call a constructor, but the assignment operator =()
.
std::string
does have an assignment operator that takes a char
, and your value 7 is converted into a char
, then the string& operator= (char c);
is called for that value. Your string will contain the ASCII BELL character.
See here for more info.
Upvotes: 1
Reputation: 2263
It's the
basic_string& operator=( CharT ch );
So the int
is implicitly being converted to a char
.
Try assigning the value 65
. Prints A
Upvotes: 1