views:

171

answers:

3

this compiles :-)

string name;
name = 1;

this does not:

string name = 1;

any thoughts?

I know that this is wrong. . . that is not the point. The first gives a smiley face.

+15  A: 

The first compiles because the assignment operator is called what has one signature of "string& operator= ( char c )" and the compiler can convert 1 into a char.

The second won't compile because it calls the copy constructor which has no compatible signature.

RobertL
+4  A: 

The second example is really initialization rather than assignment, i. e. it calls a constructor rather than operator=. Evidently class string does not have a constructor that takes an integer as an argument, but it's assignment operator is ok with it. And the reason you get a smiley face is that it is the character with the ASCII value of 1.

By the way, this is not specific to Visual Studio. Any C++ compiler should behave the same way.

Dima
+1  A: 

Not to do with the question, but why don't you (and many others) post compilable code. Would :

#include <string>
using namespace std;

int main() {
    string name;
    name = 1;
    string name2 = 1;
}

have been too much to ask for? Given that, we can see that "string" actually refers to std::string and not some random class.

anon
I think if the include isn't shown, then it's assumed to be the standard. If it's a random class, then you have to show it. Also, he got correct answers pretty quickly, thus enforcing the behavior (to everyone who sees it). I think that's how it has become the norm.
Lou Franco
I agree that a lot of code samples here aren't complete enough, but for something this simple more wasn't necessary. Furthermore, this shouldn't be an answer, but a comment.
krdluzni
For me it's not so much the guesswork what `string` refers to, but the fact that I have to make a compilable example from it myself in order to toy with it. I greatly appreciate being handed a ready-made example and I'm more likely to look closer at the question if I have.
sbi
Well, I think it is a bad norm. I can't see any reason for not posting compilable code, for simple questions like this. And actually, for more complex questions the need for real code is even more pressing.
anon
I apologize. My logic was for clarity, I did not consider tinker-ability, which in retrospect is probably more desirable for an audience of programmers.
Nona Urbiz
@Nona Sorry - I wasn't trying to pick on you but to make a general point.
anon