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 secondconstat the end of the declaration):These are two different things: The
constreturn value by itself would not be needed in the presence of a non-constmethod (since the non-const return value can always be casted tò theconstversion).But not having a
const-version of the operator would mean, that you couldn't use it onconststring objects.The
constresult is just a result of theconstness of the operator itself: if you have aconststring 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 aconststring).