3

I am having trouble understanding the difference between Array obj; and Array* obj = new Array; while overloading the array index operator []. When I have a pointer to the object, I get these error messages on VS 2010.

error C2679: binary '=' : no operator found which takes a right-hand operand of type 'int' (or there is no acceptable conversion)
could be 'Array &Array::operator =(const Array &)' while trying to match the argument list '(Array, int)'

#include <iostream>
class Array
{
    int arr[10] ;

    public:
       int& operator[]( int index )
       {
           return arr[index] ;
       }
};

int main()
{
    //Array* obj = new Array; Error

    Array obj;   // Correct
    for( int i=0; i<10; ++i )
        obj[i] = i;

    getchar();
    return 0;
}

Can some one explain the rationale between the two kind of instances for operator overloading? Thanks.

1

2 Answers 2

11

In case of Array *obj, obj[i] is the equivalent of *(obj+i), so it evaluates into an Array object.

You would have to do

int main()
{
    Array* obj = new Array;

    for( int i=0; i<10; ++i )
        (*obj)[i] = i;

    getchar();
    return 0;
}
Sign up to request clarification or add additional context in comments.

1 Comment

"so it evaluates into an Array object" is a very strange and vague claim. I'd say it assumes obj is first in a contiguous array of Arrays, and moves to the (i+1)th (array indexing being 0 based). What then happens is that it tries to assign i directly into that the Array object at that address, and there's no Array::operator=(int) nor Array(int) constructor so that's not possible. Just as well ;-), as a silent error like that would create undefined run-time behaviour and be harder to notice and fix.
3

You defined operator[] for Array, not for Array*. In the commented-out code, you create an Array*. In fact, you cannot overload an operator for any pointer type. Applying [] to a pointer treats it as an array, converting the array indexing into pointer arithmetic. Thus, applying [] to an Array* yields an Array (really an Array&). You can't assign an int to an Array because you didn't define that (and don't want to, either).

Modern, well-written C++ uses the keyword new very seldom. You should not be suspicious that your C++ code doesn't contain the keyword new. You should be suspicious every time it does!

Comments

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.