http://cplusplus.com/reference/string/basic_string/operator[]
I understand that it's advantageous to have a second version which returns const
to prevent warnings when a const
result is required and to mitigate casting but if the function already provides a non-const
method (method-- not result) then what is the point of declaring the const
-result method const
?
You need to understand, that the second (
const
) version not only returns a different result but is also marked itself asconst
(this is the secondconst
at the end of the declaration):These are two different things: The
const
return value by itself would not be needed in the presence of a non-const
method (since the non-const return value can always be casted tò theconst
version).But not having a
const
-version of the operator would mean, that you couldn't use it onconst
string objects.The
const
result is just a result of theconst
ness of the operator itself: if you have aconst
string and use the operator to get a reference to a single character, clearly this reference must also beconst
(if not, you could change single characters within aconst
string).