Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can write expressions like string s = "xxx" in C++?

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;
like image 836
jiafu Avatar asked Nov 23 '25 03:11

jiafu


1 Answers

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!

like image 70
templatetypedef Avatar answered Nov 25 '25 17:11

templatetypedef