An oft-overlooked feature of operator overloading in C++ is that certain operators often come in pairs. Take the classic example, the subscript operator:
// Of course, if this were real C++ we would
// most probably be using an STL container for this.
class IntList
{
public:
const int& operator[](unsigned index) const; // inspect only
int& operator[](unsigned index); // inspect or mutate
};
The two operators are nearly identical, with the only difference being the fact that one of them is a const method. In other words, we have performed const-overloading. Why do we do this?
Imagine that we have a constant object of type IntList. We can only call const methods on the object, as we are not allowed to modify a const object. Let's see how this helps the compiler help us:
const IntList list;
list[3] = 3; // Error! The compiler automatically stops us from trying this.
// As the const operator is used, we get an error from trying to
// assign to a constant value.
int i = list[3]; // This is fine! Bear in mind that we couldn't even do this
// without the const operator overload.
This works out great! The compiler will use the correct operator overload for const objects, and will prevent you from doing anything crazy. [] isn't the only operator that comes in pairs. You will most likely apply the same ideas to other operators that apply mutator/inspector semantics.