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];
A postfix expression (operand followed by the operator) followed by an expression in square brackets [ ] is a subscripted designation of the array element . The definition of the array subscript operator [ ] is that if a is an array and i is an integer then a[i] =*(a+i) .
Use a subscript operator to access one or more elements in an array. You can access a specific element or a range of elements in an array.
The Subscript or Array Index Operator is denoted by '[]'. This operator is generally used with arrays to retrieve and manipulate the array elements. This is a binary or n-ary operator and is represented in two parts: postfix/primary expression.
As an alternative to using the traditional array index notation, you can also use a pointer to access and interact with the elements in an array. The process begins by making a copy of the pointer that points to the array: int *ptr = A; // ptr now also points to the start of the array.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With