Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

subscript operator on pointers

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];
like image 998
Lodle Avatar asked May 11 '10 04:05

Lodle


People also ask

What is subscript operator in C?

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) .

What is the use of subscript operator?

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.

What is subscript index in C++?

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.

Can you use array notation with a pointer?

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.


1 Answers

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.

like image 170
James McNellis Avatar answered Oct 23 '22 21:10

James McNellis