3

I often see that:

string str = "123";

My question is if string is a class type, why can we directly set it equal to "123" instead of using new or directly initialize it?

I am used to seeing something like

classType *pt = new classType;
classType pt = classType();

not

classType s = value;
templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065
jiafu
  • 6,338
  • 12
  • 49
  • 73

1 Answers1

9

The C++ string type has an implicit conversion constructor that accepts as input a const char *. Consequently, it is legal to initialize a C++ string using a C-style string, because C++ will interpret this as a call to the implicit conversion constructor.

In this case, the code

string str = "123";

is equivalent to

string str("123");

which more explicitly looks like a constructor call.

Note that it is extremely rare to see something like

classType p = classType();

The more proper way to say this would be to just write

classType p;

which implicitly calls the default, no-argument constructor.

Hope this helps!

Captain Obvlious
  • 19,754
  • 5
  • 44
  • 74
templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065
  • is string str = "123" is different with string str("123")? due to direct initial or copy initial? – jiafu Apr 25 '13 at 01:14
  • 2
    @jiafu- The two should be completely equivalent to one another. – templatetypedef Apr 25 '13 at 01:14
  • why? I know int x(1) is different with int x=1, why in this case it is same? – jiafu Apr 25 '13 at 01:20
  • 2
    `int x = 1` and `int x(1)` are equivalent in c++ because they are built in types. Check out this link for more on the different between copy initialization and assignment initialization: http://stackoverflow.com/questions/1051379/is-there-a-difference-in-c-between-copy-initialization-and-direct-initializati – OGH Apr 25 '13 at 01:29