Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overloading operator []

Let's say I have a container class called MyContainerClass that holds integers. The [] operator, as you know, can be overloaded so the user can more intuitively access values as if the container were a regular array. For example:

MyContainerClass MyInstance;
// ...
int ValueAtIndex = MyInstance[3]; // Gets the value at the index of 3.

The obvious return type for operator[] would be int, but then the user wouldn't be able to do something like this:

MyContainerClass MyInstance;
MyInstance[3] = 5;

So, what should the return type for operator[] be?

like image 890
Maxpm Avatar asked Nov 29 '22 18:11

Maxpm


2 Answers

The obvious return type is int& :)

For increased elaboration:

int &operator[](ptrdiff_t i) { return myarray[i]; }

int const& operator[](ptrdiff_t i) const { return myarray[i]; }
// ^ could be "int" too. Doesn't matter for a simple type as "int".
like image 171
Johannes Schaub - litb Avatar answered Dec 04 '22 09:12

Johannes Schaub - litb


This should be a reference:

int &
like image 40
Eric Fortin Avatar answered Dec 04 '22 10:12

Eric Fortin