reference and const reference returned from operator in C++ -


i not understand why need 2 versions of functions return reference - 1 const , other not. example in code:

const char& string::operator[](int index) const {     verify_index(index);     return data[index]; }  char& string::operator[](int index) {     verify_index(index);     return data[index]; } 

if had const, wouldn't able example str[i] = value. problem having non-const reference, can please give example?

thanks

if had nonconst overload, unable use [] synax on const strings.

void print_first(const std::string& word) {     std::cout << word[0]; //like } 

if have const overload, unable use [] syntax modify string:

void edit_first(std::string& word) {     word[0] = 'a'; } 

if made const overload returns mutable char, that's worse!

void edit_first(const std::string& word) {     word[0] = 'a'; //wait, thought word const? } 

it's frustration have add 2 overloads, 90% of code can shared (as did verify_index), or end being two-liners.

(there fourth combination of nonconst overload returns const char, that's harmless , useless so... yeah.)


Comments

Popular posts from this blog

basic authentication with http post params android -

vb.net - Virtual Keyboard commands -

css - Firefox for ubuntu renders wrong colors -