User-defined conversions sequence

  • A+

Before I studied the explicit keyword, my teacher said: "compiler doesn't execute consecutive user defined conversion". If it is true, are there any errors in my code? Or have I misunderstood my teacher? I'm working in VS2017.

#include<iostream> #include <string>  class Myclass { public:     Myclass() {         std::cout << "Myclass" << std::endl;     } };  class Myclass1 { public:     Myclass1(Myclass m) {         std::cout << "Myclass1" << std::endl;     } }; class Myclass2{ public:     Myclass2(Myclass1 m) {         std::cout << "Myclass2" << std::endl;     } };  int main() {     Myclass2 m2 = Myclass{}; }  


compiler doesn't execute consecutive user defined conversion

Your teacher is right. In your code sample it means Myclass cannot be converted to Myclass1 when you assign in:

Myclass2 m2 = Myclass{}; 

Because constructor expects Myclass1 when creating Myclass2, and compiler cannot consecutively convert Myclass to Myclass1 and then use it for creating Myclass2. But if you have following line:

Myclass1 m2 = Myclass{}; 

It will work, because constructor of Myclass1 takes Myclass as argument.


You may ask why this works:

Myclass2 m2 {Myclass{}}; 

Because in this case, constructor is called and conversion can be done implicitly unless you declare Myclass1 as explicit which will fail code compilation (Thanks Fureeish for reminder), but in:

Myclass2 m2 = Myclass{}; 

is like calling copy-constructor which needs reference. so if you write it like this, it will work:

Myclass2 m2 = Myclass1(Myclass{}); 

As EVG mentioned, Myclass2 m2 = Myclass{}; is accepted by VS 2017 if the conformance mode (/permissive-) is not activated.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: