Here is how the code looks:
using namespace std;
class dummy{
public:
int x;
explicit dummy(int x = 0) : x{ this->x = x } {}; //explicit has no effect here
};
class myClass {
public:
operator int(); //<---problematic conversion
explicit operator dummy();
};
myClass::operator int() {
return 10;
}
myClass::operator dummy(){
return dummy(9);
}
int main() {
myClass mc1;
dummy val = (dummy)mc1;
cout << "mc1 int cast: " << mc1 << endl;
cout << "val.x: :" << val.x << endl;
std::cin.get();
return 0;
}
I'm using ms vs compiler here and getting c2440 (type cast error). To my understanding, I'm not doing anything wrong syntax-wise. The problem here is that it works fine if I remove the implicit conversion: operator int()
and its respective function out of the code.
ie:
using namespace std;
class dummy{
public:
int x;
explicit dummy(int x = 0) : x{ this->x = x } {}; //explicit has no effect here
};
class myClass {
public:
//operator int();
explicit operator dummy();
};
/*
myClass::operator int() {
return 10;
}*/
myClass::operator dummy(){
return dummy(9);
}
int main() {
myClass mc1;
dummy val = (dummy)mc1;
//cout << "mc1 int cast: " << mc1 << endl;
cout << "val.x: " << val.x << endl;
std::cin.get();
return 0;
}
this will produce the following output (as expected):
val.x: 9
Edit: explicit keyword was missing in the second example. The output is the same