Skip to main content

Overload index operator [] for array class

Short answer

Overload operator[] with a bounds check, returning an int& reference to the array element. This allows both input (cin >> a[i]) and output (cout << a[i]). Sample elements 10 20 30 40 50 are read and displayed correctly.

Create a class having an array as member. Overload index operator ([ ]) to input and display the elements in the array.

The subscript operator [] is overloaded as a member function that takes the index and returns a reference (int&). Returning a reference lets the same function be used on both sides of an assignment: a[2] = 10; (input) and cout << a[2]; (display). A bounds check makes the class safer than a plain array.

#include <iostream>
#include <cstdlib>
using namespace std;

const int SIZE = 5;

class Array {
    int arr[SIZE];
public:
    int& operator[](int i) {
        if (i < 0 || i >= SIZE) {
            cout << "Index out of range" << endl;
            exit(1);
        }
        return arr[i];
    }
};

int main() {
    Array a;
    cout << "Enter " << SIZE << " elements:" << endl;
    for (int i = 0; i < SIZE; i++)
        cin >> a[i];                 // a.operator[](i) used as lvalue

    cout << "Elements are: ";
    for (int i = 0; i < SIZE; i++)
        cout << a[i] << " ";         // a.operator[](i) used as rvalue
    cout << endl;
    return 0;
}

Sample run:

Enter 5 elements:
10 20 30 40 50
Elements are: 10 20 30 40 50

a[i] is translated to a.operator[](i). The subscript operator can be overloaded only as a member function.

✓ Answer checked by Claude Opus 5.5 (high effort)

All Object Oriented Programming chapter 5 questions →