I have done a little experiment and I don’t understand the output !
class C {
public:
operator int() const { std::cout << "I'm const" << std::endl;}
operator int(){ std::cout << "I'm not const" << std::endl;}
};
void f(int){};
int main()
{
f(C());
}
Why does this output "i'm not const" ? Shouldn’t the first cast of the C object, which is an rvalue and therefore const, be prioritary?
Thanks ! 🙂
Edit : If it can make the question more precise :
In constrast :
void g(C const &){ std::cout << "I take a const" << std::endl; };
void g(C &){ std::cout << "I take a non const" << std::endl; };
g(C()) outputs “I take a const”.
A temporary isn’t constant:
If you want to refer to it constantly, cast it:
The point is that the object whose member function (here the conversion operator) is called is not constant. This has nothing to do with the result of the conversion.
The result isn’t actually required to be constant, either. Suppose we add another class: