icepopo icepopo - 11 months ago 86
C++ Question

Operator[][] overload

Is it possible to overload

operator twice? To allow, something like this:
(like in a two dimensional array).

If it is possible, I would like to see some example code.

Answer Source

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

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

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

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

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

    int** _arrayofarrays;

Then you can use it like:

ArrayOfArrays aoa;

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