Home > OS >  Implicit conversion from char to int for constructors in C
Implicit conversion from char to int for constructors in C

Time:11-11

class A {
    int x;
    std::string s;
public:
    A(std::string _s): x(0), s(_s) {
        std::cout << "\tA(string)\n" ;
    }
    A(int _x): x(_x), s("") {
        std::cout << "\tA(int)\n" ;
    }
    A(const A &other): x(other.x), s(other.s) {
        std::cout << "\tA(A& other)\n" ;
    }
};

int main() {
    std::string str = "Hello";
    A obj_1(str);
    A obj_2 = str;
    A obj_3(10);
    A obj_4 = 10;
    char ch = 'a';
    A obj_5 = ch;               // How is this working?
    // A obj_6 = "Hello";        // And not this?
    const char *ptr = "Hello";
    // A obj_7 = ptr;            // or this?

    return 0;
}

On executing this code, the output is:

        A(string)
        A(string)
        A(int)
        A(int)
        A(int)

As far as I understand, obj_1 and obj_3 are created directly by using the respective ctors. For obj_2 and obj_4, the compiler does an implicit conversion by calling their respective ctor (so only 1 implicit conversion is required in each case). However, for obj_5 the compiler first has to convert from char to int and then one more implicit conversion to call the int-ctor. But C standard allows only 1 implicit conversion. So what is happening here?

Also, in that case "Hello" should first get converted to a std::string then one more implicit conversion to call the string-ctor. But this doesn't work.

CodePudding user response:

But C standard allows only 1 implicit conversion.

Thats not correct.

From cppreference:

Implicit conversion sequence consists of the following, in this order:

  1. zero or one standard conversion sequence;
  2. zero or one user-defined conversion;
  3. zero or one standard conversion sequence.

From the language point of view, const char[N] -> std::string (or const char* to std::string) is a user-defined conversion. Hence, the commented out lines are errors. On the other hand,

A obj_5 = ch;               // How is this working?

is fine, because there is only a single user-defined conversion involved.

  • Related