The title says it all. However, please take string as a placeholder for any class.
std::string s1("hello"); // construct from arguments
std::string s2 = "hello"; // ???
std::string s3; // construct with default values
s3 = "hello"; // assign
I wonder if the statement for s2 does the same as for s1 or for s3.
The case of s2 is copy initialization. It's initialization, not assignment as case of s3.
Note that for std::string, the effect is the same for s1 and s2, the apporiate constructor (i.e. std::string::string(const char*)) will be invoked to construct the object. But there's a different between copy intialization and direct initialization (the case of s1); for copy intialization, explicit constructor won't be considered. Assume that std::string::string(const char*) is declared explicit, that means the implicit conversion from const char* to std::string is not allowed; then the 2nd case won't compile again.
Copy-initialization is less permissive than direct-initialization: explicit constructors are not converting constructors and are not considered for copy-initialization.
In this case, s1 and s2 do exactly the same thing: they both call the constructor to const char*. (Some folk prefer to use = for clarity).
For s3, the default constructor is called, followed by operator= to const char*.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With