Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does copy-initialization fail for a type with a converting construtor, when list-initialization is valid? [duplicate]

Consider the following code

// C++ 14.

struct A {
    A(int i) {}
};

struct B {
    B(A a) {}
};

int main(){
    A a = 5;
    B b1 = 5; // error
    B b2 = a;
    B b3 { 5 };
    B b4 = { 5 };
    return 0;
}

Unsurprisingly, most of those initializers are valid. But why the second one gives an error? Looks like the equal initializer only supports one level of implicit conversion?

Does this behaviour still hold in the latest c++ version?

like image 709
TSs Avatar asked Aug 31 '25 01:08

TSs


1 Answers

You are only ever allowed to do up to one user defined conversion in an implicit conversion sequence. All of the lines obey that except number two.

A a = 5;
// okay, create an A from int

B b1 = 5;
// not okay, create an A from an int and then create a B from an A

B b2 = a;
// okay, create a B from an A

B b3 { 5 };
// okay, this is direct initialization of a B so 5 is allowed to be
// converted to an A and then that can be used to construct the B

B b4 = { 5 };
// okay, same as above except you are directly initializing a temporary
like image 145
NathanOliver Avatar answered Sep 02 '25 16:09

NathanOliver