Jerome Baldridge
Jerome Baldridge

Reputation: 518

Why can I assign an Int to a String without compiler error?

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

Answers (3)

manlio
manlio

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

riverhorse
riverhorse

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

anorm
anorm

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

Related Questions