14.5. Subscript OperatorClasses 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.
Providing Read and Write AccessOne 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.
Prototypical Subscript OperatorThe following class defines the subscript operator. For simplicity, we assume the data Foo holds are stored in a vector<int>: 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 }; The subscript operators themselves would look something like: 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 }
![]() |