Jonathan Wood
Jonathan Wood

Reputation: 67203

Overloading Square Brackets Operator to Accept Value

I'm writing a collection class. I want to overload the square brackets operator ([]) to provide access to elements in the collection.

int operator[](int i)
{
    // Do stuff here
}

My problem is that I don't see how to write this so that I could use this operator to accept a value:

myClassInstance[0] = value;

I see no way to declare the square brackets operator with an additional argument (the value to assign to the element).

I know I can simply return int& and the caller can assign a value to that, but internally each element is stored in a different format than the one made public.

Is this even possible?

Upvotes: 7

Views: 5600

Answers (3)

Helldenis
Helldenis

Reputation: 19

write:

    int& operator[](int i)
    {
        // Do stuff here
    }

Upvotes: 1

bmargulies
bmargulies

Reputation: 100050

Return a reference to an object that has an operator = that can stuff the int where it needs to go. Look at the boolean vector trickery in STL for an example, if not necessarily a wonderfully exemplary example.

Upvotes: 2

James McNellis
James McNellis

Reputation: 355069

Write an int_proxy class that is implicitly convertible to int and is assignable from int. You'll need at least two member functions:

operator int();
int_proxy& operator=(int);

In this proxy class, store whatever information you need to be able to retrieve and set the value in the container. Do the retrieval in the conversion operator and the assignment in the assignment operator.

Upvotes: 9

Related Questions