c++ – Operator overload [][]


It's easy to overload the [] operator.

But what if I need a two-dimensional array?

How to overload the [][] operator?

If I write [] with two parameters – swears. If I write [][] – swears:

error C2092: тип элемента массива "[]" не может быть функцией

this is how I declare:

double& operator [][] (const int i, const int j);


You are not the first to be interested in this problem; this question even got into the official list of frequently asked questions on C ++ at one time.

The famous C++ FAQ advises using operator () :

Use operator() , not operator[] .

If you have a multidimensional array, the cleanest solution is to use operator() rather than operator[] . The reason is that operator[] always takes one parameter, while operator() takes any number of them (in the case of a rectangular matrix, you need two).

Here and here is an explanation of why parentheses are better than two pairs of square brackets.

Brief summary:

  1. square brackets require the creation of an intermediate object representing a table row, which imposes a restriction on the physical location of data in the main class.
  2. parentheses are obviously not worse under any circumstances, and sometimes better
  3. using native C++ syntax is better
  4. validation of input parameters is easier, which improves code quality
Scroll to Top