Imagine I have a class “Window” with a member function “show” which causes the underlying window to become visible on the screen.
Because I’m calling an underlying windows API to achieve this I’m not in any way altering the state of my “Window” object and yet clearly there is a large, obvious change in state of my window caused by calling this ( a window appearing on the screen and being able to be interacted with by users)
So I should declare my function as –
void Window::show() const;
because as far as the Window object is concerned this function doesn’t change any state and therefore can be called on “const Window” objects. But somehow that doesn’t seem right as calling that function clearly in some sense changes the state of the object.
What you’re probably grappling with is that C++ has no notion of purity, that is, whether or not a function has side-effects.
constmember functions only make the promise that the state of the object itself will not be modified.However, some objects logically consist of more state than what the instance actually contains. This comes up very often when an object’s role is to interact with state managed by another library—especially a GUI library.
Therefore, while
show()can incidentally be markedconst, it logically should not be. If it were trulyconst, then you would expect a function such asis_visible()to return the same value both before and after the call toshow(), and clearly that is not the case.In other words,
constfunctions are those that change nothing about the object that you can observe through its public interface. That’s the reasoning behind, for example, marking some member functionsconstbut using amutablemember to do internal bookkeeping.