How to overload []

Hi,

I'm curious how I would go about overloading []. I have an exam tomorrow, and on last years exam the prof asked the following question:

Make a class that hold a private vector<int> - he then lists a bunch of requirements for the class, one of which is overloading the [] operator both ways so that you could go:

foo[4] = 6;

or int i = foo[4];

How would I go about this?

Thanks!
In order for foo[4] = 6; to work, operator[] has to return a non-const reference. Technically you could use the same method for the second line above too, however it is more usual to make a second operator[] that is a const method and returns the int by value instead of by reference.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class F {
  int *value;
  ...
 public:
  int& operator[](int index) {
    ...
    return value[index];
  }
  ...
};

int main() {
  F foo;
  foo[4] = 6;

  return 0;
}
Topic archived. No new replies allowed.