[] operator overloading

Hey. i have a class with 2D array inside. I'd like to overload [] operator that will allow me to access any member of this array (like int a=myarr[1][2]). How can i do that? thanks.
This is bad encapsulation.

I would recommend
 
int a = myClass->getValue(X, Y);


This would allow you to put bounds checking on X and Y before trying to access your array. Allow you to prevent out of bounds exceptions and memory issues.

Z.
I don't agree with Zaita. You can do all the bounds checking in an operator [], just like another function.

It's not possible to overload "operator[][]". You have to overload "operator[]", and return some kind of proxy object, that also overload "operator[]" to get the second index.

Draft code:
1
2
3
4
5
6
7
8
9
10
11
12
class Array {
  int** data;
public:
  class Proxy {
    Array& _a;
    int _i;
  public:
    Proxy(Array& a, int i) : _a(a), _i(i) {}
    int& operator[](int j) { return _a.data[_i][j]; }
  };
  Proxy operator[](int i) { return Proxy(this, i); }
};
Ahhh touche :) You are indeed correct ropez. Although that produces some pretty nasty code =\ But operator overloading seems to always do that :P
ropez, why did you set the "Proxy" class as a public of "Array"? Can't it be a private one? And some newbie question: what is "_" char doing before "a" and "i"? Thanks you for help.

Zaita, when I overload operator() should i use int a = myClass->getValue(X, Y);
and not just
int a = myClass(X,Y);?
Zaite didn't mean to overload operator(), but to use a regular member function.

_a, _i is simply a prefix that is sometimes used to distinguish member variables from locals/parameters.

The Proxy class needs to be public because a user of Array needs to access it's operator[], which is done implicitly when using array[][].
Thanks a lot. I will definitely impelemnt this =)

Wait... "this" is an object itself or his address?
Last edited on
"this" is the address, so line 11 should actually be
 
  Proxy operator[](int i) { return Proxy(*this, i); }
Topic archived. No new replies allowed.