Search code examples
c++double-pointersubscript-operator

Overloading subscript operator and working with double-pointers?


I have the following variable that I need to work with, and have to write my own wrapper around it for an assignment. I am going beyond the assignment (since I am going to have to use this wrapper I make) and wanting to overload the subscript operator in my wrapper in order to use it with the double pointer array. What I mean in code is this:

What I have:

From given header for library:

typedef struct {        // A pixel stores 3 bytes of data:
    byte red;       //  intensity of the red component
    byte green;     //  intensity of the green component
    byte blue;      //  intensity of the blue component
} pixel;

typedef struct { 
    int   rows, cols;   /* pic size */
    pixel **pixels;     /* image data */
} image;

My class (of course included in header):

pixels& MyWrapper::operator[] (const int nIndex) {
    return Image.pixels[nIndex]; // where Image is of type image
}

Of course this won't work since the double pointer returns a pointer, which is not what I'm telling it to return, yet returning *pixels& doesn't return it either. Just to sate my curiosity and to help me understand why this isn't possible, could someone tell me how this would be implemented if it can be at all, and why it is that way? Keep in mind I don't understand pointers very well yet (I know of the basics of how they work, but thats it), and am hoping to use this to very much broaden my understanding.


Solution

  • It's not clear why you are using double indirection in the first place.

    If pixels is a double pointer to an array of pixels, you can do

    pixels& MyWrapper::operator[] (const int nIndex) {
        return (*Image.pixels)[nIndex]; // where Image is of type image
    }
    

    If pixels is a pointer to an array of pointers to arrays, then you need two indices:

    pixels& MyWrapper::operator() ( int xIndex, int yIndex ) {
        return Image.pixels[yIndex][xIndex]; // where Image is of type image
    }
    

    There are a few weird things going on here.

    • typedef class { } identifier is not good C++. Use class identifier { };, or else the class has no name, so you cannot define member functions outside the class { } scope. (Among other problems.)
    • There is no reason to make a parameter type const int. Plain int accomplishes the same thing.
    • There is no apparent reason for the double indirection. Typically in C++ we avoid the direct use of pointers. There is probably a prepackaged standard structure you can use instead.