Life time of temporary objects last until the full length of the expression in which it was created when used without references
.
Consider the following:
class My
{
int i;
public:
void increment()
{
i++;
}
};
My withOutConst()
{
return My();
}
const My withConst()
{
return My();
}
int main()
{
My ob;
withOutConst().increment(); // Case 1
withConst().increment(); // Case 2
return 0;
}
As I understand the compiler creates a temporary
object( of type const My
) to hold the return value in the above cases.
And, I am trying to modify the temporary object.
(1)
Compiles fine and
(2)
Results in a compile time error with the error:
error: passing 'const My' as 'this' argument of void My::increment() discards qualifiers
That means basically this
is of type My
and not const My
as it is called for a non-const
function.
My question:
I am trying to modify a temporary object of type const My
by calling a non-const
member function.
Then why don't I get the same error in case(1) because I am operating over an object of the type const My
in both the cases.
I understand that this is related to the return type
of the functions but am unable to fully comprehend because at the end it boils down to the function(void My::increment()
) which is trying to modify temporaries of type const My
in both the cases.
A temporary has a type, that type can be const, and it can be non-const. You can call a non-const member function only on a non-const object.
withOutConst()
yield a temporary of typeMy
,withConst()
yields a temporary of typeconst My
.Maybe you have the misconception that a temporary is always
const
? If that is the case, then it is wrong.