Its unclear to me whether a temporary assumes type of const or not, in an expression as shown below.
#include <iostream>
class X {
public:
X(int a) { i = a; cout << "X(int) [" << (int)this << "]" << endl; }
X& operator+(const X& x)
{
i += x.i;
cout << "X operator+(const X&) [" << (int)this << "]" << endl;
return *this;
}
~X() { cout << "~X [" << (int)this << "]" << endl; }
private:
int i;
};
int main()
{
X x = X(3) + X(4);
cout << "done" << endl;
return 0;
}
X(3)
behaves like non-const (because I can call operator+
, while X(4)
behaves like const(because, it needs const argument in operator+
).
Can someone clarify, what is the right understanding?
When it comes to class types, when you create a temporary of const type, that temporary will be const. And when you create a temporary of non-const type, that temporary will be non-const. That's it. I.e. as far as the exact type is concerned, there no connection between const and temporaries at all. Temporary of class type never assumes const by itself. It is you who can explicitly impose const on it.
In your example nether X(3)
nor X(4)
is const. Since X(3)
is not const, you can call a non-const method on it.
It is not correct to say that your X(4)
"behaves as const". There's no indication that it "behaves as const" in your example whatsoever. Just because you were able to initialize a const reference with something does no mean that that something is const.
In your question you state that you "need const argument in operator+
". That's incorrect. You don't need const argument in your operator+
. Your parameter x
is declared as const reference. A const reference can be easily bound to const arguments as well as to non-const arguments. In your case const reference parameter x
is bound to a non-const temporary argument X(4)
.