Search code examples
c++conversion-operator

automatic conversion from string to myclass


I have defined a class

class Version
{
public:
        Version(std::string versionStr)
        {
            //do something
        }
}

I want to be able to use it as follow

void foo(Version v1) {//do somthing};
void main()
{
    foo("test");
}

I would like that v1 becomes an object as if I have done:

void main()
{
    Version v1("test");
    foo(v1);
}    

is that possible?


Solution

  • The code you have has too many levels of implicit construction. "string literal" is of type const char [] and not std::string. Only one level of implicit construction occurs automatically. Try adding a constructor that takes const char * instead:

    class Version {
        // ...
        Version(const char *_vstr) : versionStr(_vstr) {}
        // ...
    }
    

    Live demo.