const
is a promise that you won't change the thing in question. You can make promises not to change a parameter, not to change the thing that a pointer points at (or a reference refers to), not to change the this
-object (in a member function), etc. For a return value, the "promise" is binding upon the caller, so it's actually more like you're disallowing the caller to change the returned thing.
This is more useful with pointers and references (especially references, since in C++ we prefer not to pass by pointer if we don't have to) than with values, since passing by value makes a copy anyway; the caller doesn't care if the called function changes its own copy of a value. But if we pass by reference, const
lets us know that the function won't change our value via the reference.
Similarly, when we return something by reference, we're generally referring to a pre-existing thing - perhaps most commonly, we return some data member by reference from a member function. In this case, const
prevents the caller from using this reference to modify the object. That, again, makes it easier to reason about what the code does, and protects against mistakes. It's common to see accessor functions in pairs: one non-const version, and one const version where both the return value and the this-object are const. (We make the this-object const by putting const
at the end of the function signature, after the closing parenthesis of the parameter list.) The meaning: "calling this function will not affect the object, as long as the caller doesn't mutate the object via the returned reference". If the caller has a const instance of the class, then only a const reference can be returned.
For more, please read http://www.parashift.com/c++-faq-lite/const-correctness.html .