Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

User-defined conversions sequence

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{};
} 
like image 916
User8500049 Avatar asked Nov 14 '18 09:11

User8500049


Video Answer


1 Answers

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.

Update:

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.

like image 128
Afshin Avatar answered Sep 24 '22 04:09

Afshin