-1
#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.

Eric
  • 336
  • 4
  • 17
Wubin Ouyang
  • 777
  • 1
  • 7
  • 9
  • Found the part answer on https://en.cppreference.com/w/cpp/language/copy_initialization and https://en.cppreference.com/w/cpp/language/copy_initialization In addition, the implicit conversion in copy-initialization must produce T directly from the initializer, while, e.g. direct-initialization expects an implicit conversion from the initializer to an argument of T's constructor. – Wubin Ouyang Nov 10 '18 at 06:49

1 Answers1

0

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*.

LuisGP
  • 431
  • 3
  • 13