Why copy-list-initialization and copy-initialization behave differently for this case?

63 views Asked by At
#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.

1

There are 1 answers

0
LuisGP On

The constructor that the compiler is looking for is:

testClass(const char* s) : str(s) 
{
    std::cout << "custom constructor 3 called" << std::endl;
}

I think your code fails because it would need two implicit conversions, assignment and const char* to const std::string&.

Additionally you should use const std::string& instead.

testClass(const std::string &s) : str(s)
{
    std::cout<<"custom constructor 2 called"<<std::endl;
}

Because in testClass t4 = "string"; you are giving a const char*.