Search

9.8 — Overloading the subscript operator

When working with arrays, we typically use the subscript operator ([]) to index specific elements of an array:

However, consider the following IntList class, which has a member variable that is an array:

Because the m_list member variable is private, we can not access it directly from variable list. This means we have no way to directly get or set values in the m_list array. So how do we get or put elements into our list?

Without operator overloading, the typical method would be to create access functions:

While this works, it’s not particularly user friendly. Consider the following example:

Are we setting element 2 to the value 3, or element 3 to the value 2? Without seeing the definition of setItem(), it’s simply not clear.

You could also just return the entire list and use operator[] to access the element:

While this also works, it’s syntactically odd:

Overloading operator[]

However, a better solution in this case is to overload the subscript operator ([]) to allow access to the elements of m_list. The subscript operator is one of the operators that must be overloaded as a member function. An overloaded operator[] function will always take one parameter: the subscript that the user places between the hard braces. In our IntList case, we expect the user to pass in an integer index, and we’ll return an integer value back as a result.

Now, whenever we use the subscript operator ([]) on an object of our class, the compiler will return the corresponding element from the m_list member variable! This allows us to both get and set values of m_list directly:

This is both easy syntactically and from a comprehension standpoint. When list[2] evaluates, the compiler first checks to see if there’s an overloaded operator[] function. If so, it passes the value inside the hard braces (in this case, 2) as an argument to the function.

Note that although you can provide a default value for the function parameter, actually using operator[] without a subscript inside is not considered a valid syntax, so there’s no point.

Why operator[] returns a reference

Let’s take a closer look at how list[2] = 3 evaluates. Because the subscript operator has a higher precedence than the assignment operator, list[2] evaluates first. list[2] calls operator[], which we’ve defined to return a reference to list.m_list[2]. Because operator[] is returning a reference, it returns the actual list.m_list[2] array element. Our partially evaluated expression becomes list.m_list[2] = 3, which is a straightforward integer assignment.

In the lesson a first look at variables, you learned that any value on the left hand side of an assignment statement must be an l-value (which is a variable that has an actual memory address). Because the result of operator[] can be used on the left hand side of an assignment (e.g. list[2] = 3), the return value of operator[] must be an l-value. As it turns out, references are always l-values, because you can only take a reference of variables that have memory addresses. So by returning a reference, the compiler is satisfied that we are returning an l-value.

Consider what would happen if operator[] returned an integer by value instead of by reference. list[2] would call operator[], which would return the value of list.m_list[2]. For example, if m_list[2] had the value of 6, operator[] would return the value 6. list[2] = 3 would partially evaluate to 6 = 3, which makes no sense! If you try to do this, the C++ compiler will complain:

C:VCProjectsTest.cpp(386) : error C2106: '=' : left operand must be l-value

Dealing with const objects

In the above IntList example, operator[] is non-const, and we can use it as an l-value to change the state of non-const objects. However, what if our IntList object was const? In this case, we wouldn’t be able to call the non-const version of operator[] because that would allow us to potentially change the state of a const object.

The good news is that we can define a non-const and a const version of operator[] separately. The non-const version will be used with non-const objects, and the const version with const-objects.

If we comment out the line clist[2] = 3, the above program compiles and executes as expected.

Error checking

One other advantage of overloading the subscript operator is that we can make it safer than accessing arrays directly. Normally, when accessing arrays, the subscript operator does not check whether the index is valid. For example, the compiler will not complain about the following code:

However, if we know the size of our array, we can make our overloaded subscript operator check to ensure the index is within bounds:

In the above example, we have used the assert() function (included in the cassert header) to make sure our index is valid. If the expression inside the assert evaluates to false (which means the user passed in an invalid index), the program will terminate with an error message, which is much better than the alternative (corrupting memory). This is probably the most common method of doing error checking of this sort.

Pointers to objects and overloaded operator[] don’t mix

If you try to call operator[] on a pointer to an object, C++ will assume you’re trying to index an array of objects of that type.

Consider the following example:

Because we can’t assign an integer to an IntList, this won’t compile. However, if assigning an integer was valid, this would compile and run, with undefined results.

Rule: Make sure you’re not trying to call an overloaded operator[] on a pointer to an object.

The proper syntax would be to dereference the pointer first (making sure to use parenthesis since operator[] has higher precedence than operator*), then call operator[]:

This is ugly and error prone. Better yet, don’t set pointers to your objects if you don’t have to.

The function parameter does not need to be an integer

As mentioned above, C++ passes what the user types between the hard braces as an argument to the overloaded function. In most cases, this will be an integer value. However, this is not required -- and in fact, you can define that your overloaded operator[] take a value of any type you desire. You could define your overloaded operator[] to take a double, a std::string, or whatever else you like.

As a ridiculous example, just so you can see that it works:

As you would expect, this prints:

Hello, world!

Overloading operator[] to take a std::string parameter can be useful when writing certain kinds of classes, such as those that use words as indices.

Conclusion

The subscript operator is typically overloaded to provide direct access to individual elements from an array (or other similar structure) contained within a class. Because strings are often implemented as arrays of characters, operator[] is often implemented in string classes to allow the user to access a single character of the string.

Quiz time

1) A map is a class that stores elements as a key-value pair. The key must be unique, and is used to access the associated pair. In this quiz, we’re going to write an application that lets us assign grades to students by name, using a simple map class. The student’s name will be the key, and the grade (as a char) will be the value.

1a) First, write a struct named StudentGrade that contains the student’s name (as a std::string) and grade (as a char).

Show Solution

1b) Add a class named GradeMap that contains a std::vector of StudentGrade named m_map. Add a default constructor that does nothing.

Show Solution

1c) Write an overloaded operator[] for this class. This function should take a std::string parameter, and return a reference to a char. In the body of the function, first iterate through the vector to see if the student’s name already exists (you can use a for-each loop for this). If the student exists, return a reference to the grade and you’re done. Otherwise, use the std::vector::push_back() function to add a StudentGrade for this new student. When you do this, std::vector will add a copy of your StudentGrade to itself (resizing if needed). Finally, we need to return a reference to the grade for the student we just added to the std::vector. We can access the student we just added using the std::vector::back() function.

The following program should run:

Show Solution

2) Extra credit #1: The GradeMap class and sample program we wrote is inefficient for many reasons. Describe one way that the GradeMap class could be improved.

Show Solution

3) Extra credit #2: Why doesn’t this program work as expected?

Show Solution

9.9 -- Overloading the parenthesis operator
Index
9.7 -- Overloading the increment and decrement operators

100 comments to 9.8 — Overloading the subscript operator

  • yayafuture

    There is a typo, in the second program,
    return m_list[nIndex];
    should be
    return m_list[index];

  • AMG

    Alex,
    I agree with you on "Extra credit #2", but on my Xcode it works as expected. I added another person to your example, and it still works. It seems dangling reference may or may not fail, and hence, may not easy to catch.
    Thanks.

    • Alex

      Yes, dangling references can be a pain to debug. They may work fine depending on how the compiler lays things out in memory, and then you’ll do something seemingly unrelated that causes the compiler to change how it does memory layout and suddenly something that appeared to be working no longer is. That can be quite difficult to find.

  • David

    Why does this work?

    Using Visual Studio v15.3.3

    • Alex

      In my solution, I create a named variable which is used as an intermediate value. In your solution, initializer list { name, ” } is implicitly converted to a StudentGrade. The end-result is the same -- yours just avoids the named intermediary by using a temporary r-value.

  • Dani

    Hi Alex,
    int main()
    {
        GradeMap grades;
        char& gradeJoe = grades["Joe"];
        gradeJoe = ‘A’;
        char& gradeFrank = grades["Frank"];
        gradeFrank = ‘B’;
        std::cout << "Joe has a grade of " << gradeJoe << ‘n’;
        std::cout << "Frank has a grade of " << gradeFrank << ‘n’;

        return 0;
    }

    why do you say this don’t work as expect ?
    i think this print as expect. i try to compile and it print :
    Joe has a grade of A
    Frank has a grade of B

    ….Thanks for your answer

  • Martin

    …(in this case, 2) an argument to the function.

    should be

    …(in this case, 2) as an argument to the function.

  • Martin

    There is a spelling mistake:

    This allows us to both get and set values of m_anList directly

  • Rohit

    Hi Alex!

    StudentGrade temp { name, ‘ ‘ };

        // otherwise add this to the end of our vector
        m_map.push_back(temp);

        // and return the element
        return m_map.back().grade;
    }

    In the above code according to me first an empty grade is stored in the temp obj and then through returning by reference this ‘ ‘ empty value(char) is replaced by the original grade. Is this correct or there is something else happening here?

    • Alex

      First an empty grade is created. Then it’s added to the std::vector (if necessary). Then the proper element is returned by reference, so that the caller can set the grade itself.

  • DenisKa

    It was bugging me why does operator[] return reference and you cleared it once again 🙂

    -Thanks Alex

  • Ayush Goel

    Hey Alex, Actually I’m having a problem understanding the output generated by my code. I used << operator overloading and ++ -- overloading, could you please help me out?

    The output was supposed to be (as I was expecting it to be)
    11,20
    12,21
    12,21
    13,22

    instead, it shows
    13,22
    13,22
    11,20
    13,22

    • Alex

      As I have said many times (and will say again): A variable with side effects applied should not be used more than once in a given statement, otherwise the results may be indeterminate. You use p1 four times in a single statement, and have side effect applied twice (once with the pre-increment and once with the post-increment).

  • sebastian

    Hello! i have one question, when i do this:

    class Class obj; i know that i created an object from the class Class called ‘obj’. But when i do this:

    class *obj = new Class;    what is the name of the object in the heap?? because this is not an anonymous object, is obj?? and the object itself lived in the heap and the pointer live in the stack?? i’m a little confused …  I asked this because i try to undertand the codes making a little diagrams of the objects  and so on.

    Best regards.

  • Chris

    Is there a reason why this works:

    But this does not?:

    It throws the following error:
    ‘return’: cannot convert from ‘const char’ to ‘char &’

    • Alex

      I can’t speak to what situations “for each” works/doesn’t work in, as it’s not part of the C++ standard. It’s something that Microsoft made up, and you should not use it.

  • Ryan

    In one of your first code examples on this page, you have the following:

    Is there any reason you did not make index a reference parameter, rather than having the function copy it in? Would it not be better for performance to always make any constant parameters referenced?

    Thanks!

  • Matt

    In the quiz section(1C), you wrote:
    "This class should take a std::string parameter, and return a reference to a char."

    Did you mean to write "function" instead of "class"?

Leave a Comment

Put C++ code inside [code][/code] tags to use the syntax highlighter