Operator[][] overload

You can overload operator[] to return an object on which you can use operator[] again to get a result.

class ArrayOfArrays {
public:
    ArrayOfArrays() {
        _arrayofarrays = new int*[10];
        for(int i = 0; i < 10; ++i)
            _arrayofarrays[i] = new int[10];
    }

    class Proxy {
    public:
        Proxy(int* _array) : _array(_array) { }

        int operator[](int index) {
            return _array[index];
        }
    private:
        int* _array;
    };

    Proxy operator[](int index) {
        return Proxy(_arrayofarrays[index]);
    }

private:
    int** _arrayofarrays;
};

Then you can use it like:

ArrayOfArrays aoa;
aoa[3][5];

This is just a simple example, you’d want to add a bunch of bounds checking and stuff, but you get the idea.

Leave a Comment