I know that it's possible to overwritew index operation [] in C++ and work with class internal data like with an array. Is it possible to overwrite [][] and to work like with two demension array ?
4 Answers
Yes, it's possible (and std::vector is an example of such a class).
You should overload operator[] in your class or structure.
In case you use positive integers to index data possible signature will be:
RETURN_TYPE operator[] (size_type n);
UPD: if you want two-dimensional data structure with non-negative integers as keys you can use vector of vectors:
std::vector<std::vector<YOUR_TYPE>> vector_name;

- 14,395
- 10
- 44
- 68
-
Do you have an example how to do it. But std::vector is not two dimension – user1913557 Jun 24 '13 at 15:44
In order to achieve it you need to overload operator[]
to return some object that have operator[]
too. For example:
class Proxy {
std::vector<int>::iterator it;
//constructor;
int operator[] (size_t pos) {
return *(it + pos);
}
}
class MyMatrix {
std::vector<std::vector<int>> v;
Proxy operator[] (size_t pos) {
return Proxy(v[pos].begin());
}
}

- 46,822
- 11
- 79
- 123
-
1Note that if you're not doing bounds checking, and you use a single dimension implementation, a pointer is an adequate `Proxy`: `int* operator[]( int i ) { return &v[ i * columns ]; }`. Similarly, if with your implementation, `std::vector
&` is a suitable proxy. – James Kanze Jun 24 '13 at 16:39
Yes indeed you can; conventionally, you would overload [] return a reference to a row-type object, and overload [] on that row-type object to yield a reference to the scalar.
You should also consider overloading pointer dereference as well in order to maintain the equivalence of [x]
and *(... + x)
.

- 231,907
- 34
- 361
- 483
-
Your second suggestion really depends on the kind of the class in question. I can't really imagine `std::vector
v(100); *(v + 7) = 5;` being legal code. – Angew is no longer proud of SO Jun 24 '13 at 15:49 -
@Angew; indeed. Hence the need to consider. If you were writing a matrix class then I think you should. – Bathsheba Jun 24 '13 at 15:57
Let's say you have an array arr
whenever you want to acess arr[x][y]
for exemple it has an equivalence of (arr[x])[y]
so first of all arr[x]
is evaluated (let's name it a
) and then a[y]
is evaluated so you have to overload just []
operator.

- 2,952
- 3
- 24
- 46
-
But (arr[x]) - must return a one dimension array, and a[y] - a value, how overload one operator for two different return types ? – user1913557 Jun 24 '13 at 16:00
-
@user1913557 array? Nop. It returns a pointer. Your left hand side of the `[]` operator is always a pointer. – Alexandru Barbarosie Jun 24 '13 at 16:37