Hi, another beginner's question...
I am reading Sams Teach Yourself C++ by Jesse Liberty and Rogers Cadenhead.
This is an example from their book:
Code:
#include <iostream>
using std::cout;
using std::endl;
class Counter {
public:
Counter();
~Counter() {}
int getValue() const { return value; }
void setValue (int x) { value = x; }
void increment() { ++value; }
const Counter& operator++();
private:
int value;
};
Counter::Counter():value(0) {}
const Counter& Counter::operator++() {
++value;
return *this;
}
int main() {
Counter c;
cout << "c is " << c.getValue() << endl;
c.increment();
cout << "c is " << c.getValue() << endl;
++c;
cout << "c is " << c.getValue() << endl;
Counter a = ++c;
cout << "a is " << a.getValue() << endl;
cout << "c is " << c.getValue() << endl;
return 0;
}
My initial confusion was:
How can the function be const if it is changing the value of the member variable?
Then I realized that it is making the returned object const, not the object that the operator is used upon. (Can you confirm this is correct statement?).
If this is in fact true so far:
Why would you even what to have a const obj to assign to another object?
I mean, it is not like the returned object would have to be const so that it could be assigned to a const obj, after all, you can assign to a const object anyway, regardless of the object on the right hand side.
Unless this is meant for the particular case where you are creating a const obj.
Is this what all this const operator declaration is really about? To support this case?
I really appreciate your clarification.
Many thanks!
Eovento