I’ve been asked in a class I’m taking to overload [] and return both a const and a non const character:
char * data_;
char & operator [] (size_t index);
const char & operator [] (size_t index) const;
I have the same implementation for both, and it compiles, but I’m pretty sure I’m missing something here:
const char & Array::operator [] (size_t index) const
{
return data_[index]; // todo: needs to be const?
}
How can I ensure the returned character is not modifiable?
The
constin the return type,const char&, ensures that the character is not modifiable via the returned reference.Note, however, that it might be preferable to return a
charinstead (i.e., acharby value, not a reference to aconst char). Returning a const reference is useful when you have a large object (because you can avoid copying lots of bytes in many cases) or in generic code (because you don’t know the size of all of the types that might show up), but when returning something known to be small (things don’t get any smaller thanchar), you can just return it by value.