Sign in to follow this  
drkpriest

subscript operator problem

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
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

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this