#include <iostream>
#include <string>
class testClass {
public:
// testClass(const char * s)
// {
// std::cout<<"custom constructor 1 called"<<std::endl;
// }
testClass(std::string s) : str(s)
{
std::cout<<"custom constructor 2 called"<<std::endl;
}
private:
std::string str;
};
int main(int argc, char ** argv)
{
testClass t0{"str"};
testClass t2 = {"string"};
testClass t4 = "string"; // error conversion from 'const char [7]' to non-scalar type 'testClass' requested
return 0;
}
It seems that copy-initialization disallows implicit conversion from const char *
to string
while copy-list-initialization and direct-initialization allow for it.
The constructor that the compiler is looking for is:
I think your code fails because it would need two implicit conversions, assignment and
const char*
toconst std::string&
.Additionally you should use
const std::string&
instead.Because in
testClass t4 = "string";
you are giving aconst char*
.