Need an explanation

Can someone explain why this code works

1
2
3
    string a;

    a = 1;


and not this one ?

 
    string a = 55;
It's a good question.


The string assignment operator has been overloaded for char so what really happens in the first code snippet is that 1 is implicitly casted to a char that is then assigned to the string.

 
a = static_cast<char>(1);

http://www.cplusplus.com/reference/string/string/operator=/


There is no string constructor that takes only a char as argument so that's why the second code snippet doesn't work. To be honest I think it's a bit inconsistent.
Last edited on
Topic archived. No new replies allowed.