Does an object lose its constant when an implicit conversion occurs?

I did a little experiment, and I do not understand the way out!

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 is this output "i'm not const" ? Should there be a first listing of a C object, which is an rvalue and therefore const is a priority?

Thanks!:)

Edit: if this can make the question more accurate:

In contrast mode:

 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 ()) prints "I accept const".

+4
source share
2 answers

The temporary value is not constant:

 C(); // not const 

If you want to constantly refer to it, do it:

 f(static_cast<const C&>(C())); 

The fact is that an object whose member function (here the conversion operator) is called is not a constant. This has nothing to do with the result of the conversion.

Actually, the result is not permanent. Suppose we add another class:

 class D { }; class C { // ... operator D() { return D(); } }; int main() { D d; static_cast<D>(C()) = d; // OK: assign d to the result of the conversion // static_cast<int>(C()) = 6; // Error: left-hand side is not an lvalue } 
+4
source

This may surprise you, but it is completely legal C ++:

 class C { } ; int main() { C d ; C() = d ; } 

See this ideone link for proof. So C() is an lvalue.

+1
source

All Articles