• Advertisement
Sign in to follow this  

subscript operator problem

This topic is 4922 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Say if i had a pointer class which was a reference counter and a dynamic array class, how would i override the ctor in the array class to use the [] operators.

template<class T>
class Pointer
{
private:
    T* object;
public:
    operator T*()
    {
        return (object);
    }
    // other functions here, emitted for ease of reading
};

template<class T>
class Array
{
private:
    T* array;
    unsigned long arraySize;
public:
    Array(unsigned long size)
    {
        arraySize = size;
        array = new T[size];
    }
    T& operator [](size_t index)
    {
        return (array[index]);
    }
    operator T*()
    {
        return (array);
    }
    // other functions here, emitted for ease of reading
};

int main()
{
    Pointer<Array<int> > myarray;
    myarray = new Array<int>(5);
    
    myarray[4] = 6;

    return0;
}



Why is it that the array ctor gets called at the line myarray[4]=6; instead of the [] overload ?? and how can i access the [] overload method??

Share this post


Link to post
Share on other sites
Advertisement
Guest Anonymous Poster
(*(myarray()))[4] = 6;

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
sorry,

(*((Array*)myarray))[4] = 6;

Share this post


Link to post
Share on other sites
i figured it out..

i just took out the pointer cast method and you can access it like this:

(*(myarray))[4] = 6;

this de-references the object pointer in Pointer and runs the de-reference overload method in Array which passes it to the subscript operator method. yippee.. however i think i might just incorporate the Pointer stuff into Array..

cheers for that man.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement