Search code examples
c++operator-overloadingoverloadingstdfunction-qualifier

Why is std::basic_string::operator[] simultaneously a const/non-const member function?


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?


Solution

  • You need to understand, that the second (const) version not only returns a different result but is also marked itself as const (this is the second const at the end of the declaration):

    const_reference operator[] (size_type pos) const;
    

    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ò the const version).

    But not having a const-version of the operator would mean, that you couldn't use it on const string objects.

    The const result is just a result of the constness of the operator itself: if you have a const string and use the operator to get a reference to a single character, clearly this reference must also be const (if not, you could change single characters within a const string).