class Dynarr { private: double * arr; int size; public: double & operator[](int pos) { cout << " hey " << size << endl; return arr[pos]; }; Dynarr * operator=(Dynarr * rhs) { *this = Dynarr(rhs->size, rhs->arr); }; }; int main() { double * darr = new double[5]; darr[0] = 0; darr[1] = 1; darr[2] = 2; darr[3] = 3; darr[4] = 4; Dynarr * arrr1 = new Dynarr(5, darr); cout << arrr1[1] << endl; system("pause"); return 0; } 

As in line

 cout << arrr1[1] << endl; 

access the second element of the arr array?

  • one
    (*arrr1)[1] since arrr1 is a pointer to an instance of a class with an overloaded operator. - VTT

1 answer 1

There are actually two options: as you have already written,

 (*arr1)[1] 

and

 arr1->operator[](1) 

But I would also like to note that it is worth having two overloaded operators - one for a constant object:

 double & operator[](int pos) { cout << " hey " << size << endl; return arr[pos]; }; double operator[](int pos) const { cout << " hey " << size << endl; return arr[pos]; }; 

Well, it would be nice to check if pos does not go beyond the bounds of the array.