C++ overloading array operator

Solution 1:

It is idiomatic to provide couple of overloads of the operator[] function - one for const objects and one for non-const objects. The return type of the const member function can be a const& or just a value depending on the object being returned while the return type of the non-const member function is usually a reference.

struct Heap{
    int H[100];
    int operator [] (int i) const {return H[i];}
    int& operator [] (int i) {return H[i];}
};

This allows you to modify a non-const object using the array operator.

Heap h1;
h1[0] = 10;

while still allowing you to access const objects.

Heap const h2 = h1;
int val = h2[0];

Solution 2:

You can return references to what should be set. Add & to the return type.

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

Solution 3:

You should return by reference. With your current version you are taking a copy and editing this copy which will not affect the original array. You have to change your operator overloading to this:

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