Many people overlook the fact that member functions differing only in their constness can be overloaded, but this is an important feature of C++(www.cppentry.com). Consider a class for representing a block of text:
class TextBlock {
public:
...
const char& operator[](std::size_t position) const // operator[] for
{ return text[position]; } // const objects
char& operator[](std::size_t position) // operator[] for
{ return text[position]; } // non-const objects
private:
std::string text;
};
TextBlock’s operator[]s can be used like this:
TextBlock tb("Hello");
std::cout << tb[0]; // calls non-const
// TextBlock::operator[]
const TextBlock ctb("World");
std::cout << ctb[0]; // calls const TextBlock::operator[]
Incidentally, const objects most often arise in real programs as a result of being passed by pointer- or reference-to-const. The example of ctb above is artificial. This is more realistic:
void print(const TextBlock& ctb) // in this function, ctb is const
{
std::cout << ctb[0]; // calls const TextBlock::operator[]
...
}
By overloading operator[] and giving the different versions different return types, you can have const and non-const TextBlocks handled differently:
std::cout << tb[0]; // fine — reading a
// non-const TextBlock
tb[0] = 'x'; // fine — writing a
// non-const TextBlock
std::cout << ctb[0]; // fine — reading a
// const TextBlock
ctb[0] = 'x'; // error! — writing a
// const TextBlock
Note that the error here has only to do with the return type of the operator[] that is called; the calls to operator[] themselves are all fine. The error arises out of an attempt to make an assignment to a const char&, because that’s the return type from the const version of operator[].
Also note that the return type of the non-const operator[] is a reference to a char — a char itself would not do. If operator[] did return a simple char, statements like this wouldn’t compile:
tb[0] = 'x';
That’s because it’s never legal to modify the return value of a function that returns a built-in type. Even if it were legal, the fact that C++(www.cppentry.com) returns objects by value (see Item 20) would mean that a copy of tb.text[0] would be modified, not tb.text[0] itself, and that’s not the behavior you want.