In C++, when you create a reference, it's a proxy for the original object:
int i = 0;
int& a = i;
++i;
std::cout << i << " " << a << "\n"; // prints '1 1'
++a;
std::cout << i << " " << a << "\n"; // prints '2 2'
Now, in your case:
operator++
returns a reference to the current objectCounter a = ++i;
creates a new object (no&
afterCounter
) initialized as a copy of the reference toi
If you wish a
to refer to i
, you need to change its declaration:
Counter& a = ++i;
^
This will fail to compile thought because the return value of Counter::operator++
is Counter const&
: you need to remove the const
here which is non-idiomatic for operator++
and thus:
Counter& Counter::operator++() { ++itsVal; return *this; }