0

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.

8
  • 4
    Did you instantiate B as a pointer? It doesn't look like a vector of pointers is really necessary, either. Commented Dec 27, 2012 at 10:59
  • This should work, post some real code where the problem is. Commented Dec 27, 2012 at 11:00
  • yes, B instance is created as a pointer Commented Dec 27, 2012 at 11:00
  • 1
    @tobi, Then it's returning something of type B because pointers can be indexed like arrays. Commented Dec 27, 2012 at 11:01
  • Then that's the error :) Kudos to chris. Commented Dec 27, 2012 at 11:01

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, but it doesn't look nicely. I think I will just go for A* getItem(int id) method then, because I want B to be created dynamically.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.