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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With