16

If I have a pointer to an object that has an overloaded subscript operator ([]) why can't I do this:

 MyClass *a = new MyClass();
 a[1];

but have to do this instead:

 MyClass *a = new MyClass();
 (*a)[1];
Null
  • 1,940
  • 9
  • 26
  • 32
Lodle
  • 29,817
  • 19
  • 62
  • 89

4 Answers4

19

It's because you can't overload operators for a pointer type; you can only overload an operator where at least one of the parameters (operands) is of class type or enumeration type.

Thus, if you have a pointer to an object of some class type that overloads the subscript operator, you have to dereference that pointer in order to call its overloaded subscript operator.

In your example, a has type MyClass*; this is a pointer type, so the built-in operator[] for pointers is used. When you dereference the pointer and obtain a MyClass, you have a class-type object, so the overloaded operator[] is used.

James McNellis
  • 338,529
  • 73
  • 897
  • 968
8

Because a is type pointer to a MyClass and not a MyClass. Changing the language to support your desired use would make many other language semantics break.

You can get the syntactic result you want from:

struct foo {
    int a[10];
    int& operator [](int i) { return a[i]; }
};

main() {
    foo *a = new foo();
    foo &b = *a;
    b[2] = 3;
}
msw
  • 41,609
  • 8
  • 82
  • 107
3

Simply put, with a[1] the a pointer is treated as memory containing array, and you're trying to access the 2nd element in the array (which doesn't exist).

The (*a)[1] forces to first get the actual object at the pointer location, (*a), and then call the [] operator on it.

catchmeifyoutry
  • 6,971
  • 1
  • 28
  • 25
3

Good news. You can also do...

a->operator[](1);

To add on to the preferred answer, think of operator overloading as overloading functions.

When overloading member function of a class, you remember that the pointer is not of that class type.

Stick
  • 31
  • 1