This post is part of a series of tutorials on C++

A second insanely useful operator is the subscript operator, which can be particularly useful for complex data types that include a list of indexable items. The subscript operator is what makes C++ arrays handy to access, using [index] notation.

Your basic signature for the subscript operator is as follows:

class Foo {
  value_type& operator[](int idx);
  value_type operator[](int idx) const;
};

And yes, it often makes sense to code both. What is the difference? The first version allows for read-write functionality, as it returns a reference some data member. The second version allows for read-only indexing, as it guarantees it will not change the internal contents of the class (the const on the right) and returns a copy of the data member. Sometimes, this copy is replaced with a const reference, (e.g. const value_type&), especially if value_type is a complex type itself.

Both types return various forms of value_type. This is a generic placeholder for whatever member type you’d like to return. If Foo was a tuple of some sort, it could return individual entries in the tuple. If Foo was an array type of some sort, it could return whatever entries were in the array.

Let’s see a version of this in action on our ThreeLetterWord class from the tutorials on Copy Constructors and Assignment Operators, and improved with the Stream Operators functionality too:

Note that we were able to get rid of the mundane setLetter() function we had previously used. Also, note how we coded both read and write functionality in kind of the same metaphor, avoiding a setter/getter style functionality one would usually code. In the example, I made the instance of dog a const instance to show you how the read-only version can get called too. Having the const version is also particularly useful if you pass a const reference into some other function that you’re working with, so that you can read partial class members without fear that you’re accidentally calling the read-write version.



Back to C++ Tutorials