I have a piece of code where I have both conversion constructor and conversion operator.
#include <iostream>
struct ClassFloat;
struct ClassInt{
int value;
ClassInt(int c) : value(c){std::cout << "From integer\n";};
ClassInt(ClassFloat x);
//explicit ClassInt(ClassFloat x);
};
struct ClassFloat{
float val;
explicit operator ClassInt() {std::cout << "Conversion operator called\n"; return ClassInt{999};}
//operator ClassInt() { std::cout << "Conversion operator called\n"; return ClassInt{999};}
};
ClassInt::ClassInt(ClassFloat x){
std::cout << "Conversion constructor called!\n";
value = (int)x.val;
}
int main(){
ClassFloat floatObj{3.5f};
ClassInt instance1 = floatObj; // (1)
ClassInt instance2 = (ClassInt)floatObj; // (2)
return 1;
}
- If both are non-explicit. I get a compiler error saying it is ambiguous for the first expression. Second expression calls the constructor.
- If only operator is explicit, both conversions use the constructor.
- If only constructor is explicit, second conversion calls the constructor and first one uses the operator.
- If both are explicit, I can only compile second expression. It uses the constructor.
I didn't understand why conversion operator wasn't called at the second expression in the second scenario.
I was also expecting an ambiguity error in the fourth scenario (similar to the first scenario) but constructor was picked.
I compiled using g++ 7.4.0 with -pedantic and -std=c++17 flags.