Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ less operator uses conversion operator

Tags:

c++

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?

like image 418
aguyngueran Avatar asked Jun 18 '26 05:06

aguyngueran


1 Answers

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
like image 71
Hatted Rooster Avatar answered Jun 20 '26 18:06

Hatted Rooster



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!