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.

Marlon
  • 19,924
  • 12
  • 70
  • 101
Mahesh
  • 34,573
  • 20
  • 89
  • 115

2 Answers2

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;
}
EboMike
  • 76,846
  • 14
  • 164
  • 167
  • 2
    "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. – Tony Delroy Feb 10 '11 at 02:53
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!

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153