This only compiles because you initialize the class C on its own in the line C c2 = c1; . If you had a class D that behaves the same as C and tried D d; C c = d; D d; C c = d; , it will not compile for the reason you stated: because implicit conversion requires two custom conversions. Demonstration
The reason it compiles when using the same class is because the copy-initialization operation ( A x = y; ) behaves differently when y is of type A or derived from it. In this case, the conversion constructor is selected and this constructor is then called with the y argument, which can cause an implicit conversion. The constructor call itself is not part of the implicit conversion.
So, in your code, the sequence of conversions contains only one user-defined transformation: C to int , since the C(int) constructor is called separately.
See C ++ 14 8.5 / 17:
- If initialization is direct initialization or if it is copy-initialization, where the cv-unquali fiified version of the source type is the same class as the derived class of the class, the constructors. The corresponding constructors are listed (13.3.1.3), and the best one is selected by overload resolution (13.3). The constructor selected in this way is called to initialize an object with an initializer expression or a list of expressions as argument (s).
- Otherwise (that is, for the remaining cases of copy initialization), custom conversion sequences that can convert from a source type to a destination type or (when the conversion function is used) to its derived class are listed [...]
Learn more at http://en.cppreference.com/w/cpp/language/copy_initialization .
interjay
source share