overloading [] operator

Hello Everyone!

I'm creating a class widget

1
2
3
4
5
6
7
class widget
{
    public:
        int id;
        int array[10];
        int operator[](int index) {return array[index];}
};


Now I've accross something interesting is that the [] operator when using an array or (static or dynamic, ie vector) can be used as a setter and getter, i.e.
1
2
3
int array[5] = {0, 10, 20, 30, 40}; 
array[2] = 200; //changes 2nd element to 200
cout << array[2]; //returns 2nd element 


Now how can I do that in my class?

Thanks!
return a reference rather than an an object
int& operator[](int index) {return array[index];}
Dear gestgulkan,

It worked!
But it's taking more time to execute whenever it's called in main...
Is that to be expected?
If not... Any solutions for that?
Last edited on
I wasn't particularly expecting that - what does your code look like?
Last edited on
Topic archived. No new replies allowed.