I cannot understand why for the following dummy class:
class Foo {
public:
operator double() const {
return 3.14;
}
};
when I try to compare the instances:
Foo f1;
Foo f2;
auto res = f1 < f2;
the less operator uses the existing
operator double() const
when comparing values. Where can I find the rules for this behaviour?
As mentioned in the comments, the compiler is allowed to make 1 user-defined conversion as it's doing here. It sees that it can convert both objects to double and double does have operator <, so it does that. If you only want to use your conversion operator when you (the programmer) ask for it you can add explicit:
explicit operator double() const {
return 3.14;
}
Now, the compiler may only call it when you explicitly cast it to such a type:
Foo f1;
double d = (double)f1; // conversion operator
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With