Consider this class:
Code:
class X
{
public:
int get()
{
return value;
}
void set(int n)
{
value = n;
}
private:
int value = 0;
};
Now, suppose you declare an object of this class and use it:
Code:
X x;
x.set(123);
std::cout << x.get() << std::endl;
No problem, great. But what if we have a function like this:
Code:
void foo(const X& x)
{
x.set(123);
std::cout << x.get() << std::endl;
}
That we call like this:
Now, the compiler will complain, informing us that in the context of foo, x, being a const reference, cannot be modified. Okay, so we modify it before we call the function:
Code:
void foo(const X& x)
{
std::cout << x.get() << std::endl;
}
and:
Code:
X x;
x.set(123);
foo(x);
But the compiler still complains that we're trying to modify x in a const context! The reason is that get, despite not modifying the member variable named value, remains a non-const member function, and so it could plausibly be changed to modify a member variable of the X object. Therefore, we should write:
Code:
class X
{
public:
int get() const
{
return value;
}
void set(int n)
{
value = n;
}
private:
int value = 0;
};