Multidimensional Array Classes

To anyone whose interested,

If you're like me, you've never actually thought about the inner workings of multidimensional arrays, even when you needed them for something. That changed today when I had to implement a 2D-Array class with the thought that the [][] function would be useful.

Of course, the first thing I did was assume that C++ would give me an error if I defined operator[] for a pointer to an object and then expected it to work recursively, so I defined four functions:
- 1 to return a pointer to a 1D-Array
- 1 to return a constant pointer to a 1D-Array
- 1 to return an object from the Array
- 1 to return a reference to an object from the Array

Now, this would work fine if C++ hadn't already defined multidimensional array operator[]'s recursively to return the object pointed to rather than an object itself. As such, I was hit with multiple errors because I over=coded it.

However, if you code your operator[] like this:

1
2
3
4
T* R::operator[](unsigned int i)
{
  return m_data[i];
}


where T is the object returned, R is the class name, and m_data is the array then it will work for however many dimensions you wish to work with.

Hope this was helpful
Topic archived. No new replies allowed.