tobi
tobi

Reputation: 2002

Array operator overloading

I have class A and B.

Class A has some fields. Class B is like:

class B {
public:
    A* operator[]( int id ) {
        return m_field.at( id );
    }
    /* also tried this one, but there are the same errors
    A*& operator[]( int id ) {
        return m_field.at( id );
    }
    */
private:
    vector<A*> m_field;
};

why am I getting errors while executing:

B* B_instance = new B();
B_instance[some_int]->some_field_from_A;

the errors are:

error C2819: type 'B' does not have an overloaded member 'operator ->'

error C2039: 'some_field_from_A' : is not a member of 'B'

an why do I need to have -> operator overloading and how it should looks like? It doesn't make sense to me.

I am using Visual Studio 2012.

Upvotes: 0

Views: 170

Answers (1)

Qaz
Qaz

Reputation: 61910

The indexing operator applies to something of type B, not of type B *. Therefore, to use the indexing operator, you need to first dereference your pointer (or not use one at all):

(*B_instance)[some_int]...

The reason for the error is because pointers can be indexed, as they are capable of representing an array, as in the example below:

int arr[2] = {0, 1};
int *p = arr; //array to pointer conversion
p[1] = 2; // now arr is {0, 2}

So when you index a B *, it gives you back a B that's most likely out of bounds of your imaginary array. Then, you use the arrow operator on that B object when it expects a dot operator instead. Either way if you use pointers, dereference it, then index it, then use the arrow.

Upvotes: 4

Related Questions