Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does C++ allow an integer to be assigned to a string?

I encountered an interesting situation today in a program where I inadvertantly assigned an unsigned integer to a std::string. The VisualStudio C++ compiler did not give any warnings or errors about it, but I happened to notice the bug when I ran the project and it gave me junk characters for my string.

This is kind of what the code looked like:

std::string my_string("");
unsigned int my_number = 1234;
my_string = my_number;

The following code also compiles fine:

std::string my_string("");
unsigned int my_number = 1234;
my_string.operator=(my_number);

The following results in an error:

unsigned int my_number = 1234;
std::string my_string(my_number);

What is going on? How come the compiler will stop the build with the last code block, but let the first 2 code blocks build?

like image 244
user55417 Avatar asked Jul 24 '09 13:07

user55417


People also ask

Can you assign a String to an int?

We can convert String to an int in java using Integer. parseInt() method. To convert String into Integer, we can use Integer. valueOf() method which returns instance of Integer class.

Why do we use int and String?

A String is used when you want to store character data and an int would be used when you want to store numerical data that is between -2147483648 and 2147483648. A Sting can hold a very large number of characters, but each character will take 2 bytes or 16 bits of memory to store.


2 Answers

Because string is assignable from char, and int is implicitly convertible to char.

like image 89
EFraim Avatar answered Sep 26 '22 16:09

EFraim


The std::string class has the following assignment operator defined:

string& operator=( char ch );

This operator is invoked by implicit conversion of unsigned int to char.

In your third case, you are using an explicit constructor to instantiate a std::string, none of the available constructors can accept an unsigned int, or use implicit conversion from unsigned int:

string();
string( const string& s );
string( size_type length, const char& ch );
string( const char* str );
string( const char* str, size_type length );
string( const string& str, size_type index, size_type length );
string( input_iterator start, input_iterator end );
like image 20
LBushkin Avatar answered Sep 22 '22 16:09

LBushkin