14.5. Subscript Operator
Classes that represent containers from which individual elements can be retrieved usually define the subscript operator, operator[]. The library classes, string and vector, are examples of classes that define the subscript operator.
The subscript operator must be defined as a class member function.Providing Read and Write Access
One complication in defining the subscript operator is that we want it to do the right thing when used as either the left- or right-hand operand of an assignment. To appear on the left-hand side, it must yield an lvalue, which we can achieve by specifying the return type as a reference. As long as subscript returns a reference, it can be used on either side of an assignment.It is also a good idea to be able to subscript const and nonconst objects. When applied to a const object, the return should be a const reference so that it is not usable as the target of an assignment.
Ordinarily, a class that defines subscript needs to define two versions: one that is a nonconst member and returns a reference and one that is a const member and returns a const reference.Prototypical Subscript Operator
The following class defines the subscript operator. For simplicity, we assume the data Foo holds are stored in a vector<int>:
The subscript operators themselves would look something like:
class Foo {
public:
int &operator[] (const size_t);
const int &operator[] (const size_t) const;
// other interface members
private:
vector<int> data;
// other member data and private utility functions
};
int& Foo::operator[] (const size_t index)
{
return data[index]; // no range checking on index
}
const int& Foo::operator[] (const size_t index) const
{
return data[index]; // no range checking on index
}
Exercises Section 14.5
Section 14.2.1 (p. 515).Exercise 14.18:Discuss the pros and cons of implementing this operation using the subscript operator.Exercise 14.19:Suggest alternative ways to define this operation.