Search code examples
c++operator-overloading

Operator[][] overload for two-dimensional array


Is it possible to overload [] operator twice? To allow, something like this: function[3][3](like in a two dimensional array).

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


Solution

  • 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.