I'm reading through "SAMS Teach Yourself C++ in 21 days" and I came across an example that I can't seem to understand:
#include<iostream>
using namespace std;
class Counter
{
public:
Counter() {itsVal=0;}
const Counter& operator++ ();
int GetItsVal() {return itsVal;}
private:
int itsVal;
};
const Counter& Counter::operator++()
{
++itsVal;
return *this;
}
int main()
{
Counter i;
Counter a = ++i;
cout << "a: " << a.GetItsVal() << " i: " << i.GetItsVal() << endl;
++a;
cout << "a: " << a.GetItsVal() << " i: " << i.GetItsVal() << endl;
}
Why is there an "&" in the declaration of the ++ operator? I understood this to mean that the return type of the ++ operator was a reference, but it doesn't appear to be a reference to i (since incrementing a does not increment i). I've noticed the code returns the same result if I remove both "&", but maybe it's not as efficient.