Search code examples
c++programming-languagesoperators

Why isn't ->[] an operator in C++? (a subscript operator for dereferenced array pointers)


I know asking Why? is a bad question for this site, since we can't know. However I mean it as a colloquial replacement for asking, What are some possible reasons?

I found myself writing, naturally,

foo->[i];

and being surprised to learn that it didn't work. I meant to write:

(*foo)[i];

I'm sure most see already what I mean, but to be clear, I thought

bar.subscript(i);
foo->subscript(i);

would be analogous to

bar.operator[](i);
foo->operator[](i);

But this doesn't seem to be the case. Why? I'm certain I must be looking at something the wrong way, but I can't figure out what. I know very little theory, so a layperson's explanation would be appreciated.

If there's no obvious error in my analogy though, then what are some possible reasons the designers of the language may have left the operator out? Is it ambiguous? (If so, as being mistakable for what?)


I'd like to bring some comments into an edit, as per @chris's recommendation, as I have not been as clear as I should have been:

The OP is proposing operator->[], a combination of the two.
– chris
He's asking why the thing he wants doesn't exist, not why the code he's trying to write doesn't work.
– Matthew 'Cogwheel' Orlando

Solution

  • what are some possible reasons the designers of the language may have left the operator out?

    1: Nobody proposed it. If it doesn't get proposed, it doesn't get into the language.

    2: It looks wrong. operator-> may return a pointer, but the use of it in the language is "reference this pointer and access a member". That's what the language will do with ->. So when someone sees ->[], it looks incorrect. The thing to the right of -> in every other case is some form of member identifier.

    3: Because there are far more important things to do with the language than change something minor like this.