c++classmethodsconstants

Const Methods that Return References


class Foo
{
    int Bar;

    public:

    int& GetBar() const
    {
        return Bar;
    }
}

Is it okay that GetBar is a const method? It's not actually changing anything, but it's providing the "outside world" with a means of changing it.


Solution

  • No, this is not legal. When tagging a method with const, not only are you promising you won't touch any of the internal state of the object, you also promise that you will not return anything that can be used to change the state of the object. A non-const reference may be used to modify the value of Bar outside the scope of GetBar(), hence you are implying that you cannot hold the promise.

    You must either change the method to being non-const, return a const reference, or make Bar exempt of the promise by marking it as mutable. E.g.: mutable int Bar; The mutable keyword tells the compiler that the logical constness of the object does not depend on the state of Bar. Then you are allowed to do whatever you please with it.