-2

How can I overload the [ ] operator in c++. I basically want to access the index of One-D array and return it. I tried doing this but it doesn't seem to produce the desired result.

Square Square::operator [](const Square& temp)
{
   Square obj; //creates a Square class object.

  for(int i=0;i<dimension;i++)
    {
       *obj.board = temp.board[i];

    }
return obj;

}
BartoszKP
  • 34,786
  • 15
  • 102
  • 130
  • 2
    Looks like you're using [] as a copy operator that return a new object. What you want is something that gets an index, i, and returns this.board[i]. assuming this.board exists. – kabanus Nov 26 '16 at 17:59
  • 2
    Compile with all warnings & debug info (`g++ -Wall -g`) then **use the debugger** (`gdb`). You bug might be elsewhere (also having `temp`, that is the index, being a `Square` looks strange) – Basile Starynkevitch Nov 26 '16 at 17:59
  • If `Square` contains the array you want to access, then you basically want a pass-through operator that acts like `operator[]` for normal arrays. That means it should take an index, return a reference to the actual array's element type, and use the array's `operator[]` internally. – Justin Time - Reinstate Monica Nov 26 '16 at 18:05

1 Answers1

1

Make sure you have an array of sorts in your Square class then your subscript overload would look something like this

Square& Square::operator[] (const int index)
{
   // checks if index is >= to zero AND less than your array size
   assert(index >= 0 && index < yourArray.size());
   return yourArray[index];
}

More info on assert

PS: This works under the assumption that you'll create an array of Square. If not, then update the method signature respectively.

Community
  • 1
  • 1
eshirima
  • 3,837
  • 5
  • 37
  • 61
  • 1
    Recommend a quick explanation of what assert does and probably a link to a reputable documentation page for more details. – user4581301 Nov 26 '16 at 18:19