Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clarification on Operators

I've been reading up on class operators and came across the following example:

class Array {
public:
     int& operator[] (unsigned i) { if (i > 99) error(); return data[i]; }
private:
     int data[100];
};

Does this mean I can replace [ and ] with whatever I want? For example, could I use parentheses?

Also, what is the significance of the ampersand in int& operator[]?


On a slightly less important note, would it be syntactically correct to use int& operator [] instead of int& operator[]?

like image 583
Maxpm Avatar asked Feb 26 '23 17:02

Maxpm


2 Answers

Does this mean I can replace [ and ] with whatever I want?

Nopes! Not all operators can be overloaded.

For example, could I use parentheses?

You can but you shouldn't.

Also, what is the significance of the ampersand in int& operator[]?

It means you are returning a reference to an int variable.

EDIT: On a slightly less important note, would it be syntactically correct to use int& operator [] instead of int& operator[]?

There is no difference between the two.

like image 172
Prasoon Saurav Avatar answered Mar 07 '23 02:03

Prasoon Saurav


What you are doing is defining an Array class that wrapes a simple integer array. By overloading the [] operator you can acces each element of the array as with any other array, the advantage here is that your are checking superior limit to avoid buffer overflow. The ampersand means that you are returning a reference to the array element, it allows you both assigment a value and getting a value. In c++ when you overload the [] operator dont forget both const and non-const versions:

int& operator[] (conts int a) {...}
int operator[] (conts int a) {...} const
like image 20
ArBR Avatar answered Mar 07 '23 03:03

ArBR