Sep 15, 2021 at 6:34am UTC
Why is this compiled?
(EDIT: in line no 24)
Isn't c++ is rval? even if it is lval it is not assigned to 4.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
#include <iostream>
using namespace std;
class Counter
{
private :
int val;
public :
Counter(int x=0):val(x){}
Counter operator ++(int )
{
val++;
return *this ;
}
void show()
{
cout << val;
}
};
int main()
{
Counter c ;
c++ = 4;
c.show();
}
Last edited on Sep 15, 2021 at 7:53am UTC
Sep 15, 2021 at 7:18am UTC
Note that
Counter operator ++(int )
is not the same thing as
Counter operator ++()
One is precondition increment and the other is postcondition increment.
This means you need increment
val
after
return *this
in postcondition increment operator
For example:
1 2 3 4 5 6
Counter operator ++(int )
{
Counter temp = *this ;
++val;
return temp;
}
Last edited on Sep 15, 2021 at 7:21am UTC
Sep 15, 2021 at 7:52am UTC
Ok, but my question is why line no 24 works?
Sep 15, 2021 at 8:02am UTC
On line 24 you assigned number 4 to temporary Counter
object that is destroyed on same line.
It works but number 4 is not assigned to the actual Counter
object that you have declared on line 23.
It would be assigned 4 for real if operator++ would return a reference to *this
, however it returns a temporary unnamed object.
Last edited on Sep 15, 2021 at 8:04am UTC
Sep 15, 2021 at 8:13am UTC
Thank you, but isn't that temporary Counter
rvalue? Why so?
Sep 15, 2021 at 9:38am UTC
temporary Counter
object is an xvalue which means "expiring value", which means a value which is about to be destroyed.
That temporary object is also rvalue which is a value you can't take address of.
Note that xvalue can be either glvalue or rvalue, and in this case it is rvalue.