Unary Operator Overloading

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
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
Ok, but my question is why line no 24 works?
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
Thank you, but isn't that temporary Counter rvalue? Why so?
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.
thanks
Registered users can post here. Sign in or register to post.