3

In C++, must operator []() always be a member function? If yes, why?

I read "An operator must be a member function" in book

"The C++ Programming Language Special Edition" page 287.

Aswin Murugesh
  • 10,831
  • 10
  • 40
  • 69
Andy Huang
  • 177
  • 7
  • 1
    Yes, because it is supposed to access the private members of the class. – Morwenn Jun 20 '13 at 10:04
  • You shoudl read this other post from Stack Overflow, it is very interesting : http://stackoverflow.com/questions/4421706/operator-overloading/4421719#4421719 – ChristopheLec Jun 20 '13 at 10:05
  • it shouldn't be. saying that it has to access private members is pure speculation... – Karoly Horvath Jun 20 '13 at 10:06
  • 1
    @Morwenn It can order pizza, too. – jrok Jun 20 '13 at 10:07
  • @jrok Talking about pizza and private members at once is kind of awkward. – Morwenn Jun 20 '13 at 11:03
  • @Morwenn, yes the `[]` is overloading to access private members of the class, but why can't it be a friend function? A friend function can also access private variables and some operators are overloaded using friend functions. – Simon Z. Nov 27 '20 at 04:28
  • @SimonZ If I had to hazard a guess I would say that it is because the standard would then have to introduce the new exception of "function that can only be in-class or friend" and that it had no obvious advantage over just restricting it to in-class everywhere consistently. It's an old design decision though, I don't know whether the rationale is still somewhere. – Morwenn Nov 27 '20 at 09:10

1 Answers1

9

From the C++ draft:

13.5.5 Subscripting [over.sub]

operator[] shall be a non-static member function with exactly one parameter. It implements the subscripting syntax

postfix-expression [ expression ]

Thus, a subscripting expression x[y] is interpreted as x.operator for a class object x of type T if T::operator exists and if the operator is selected as the best match function by the overload resolution mechanism (13.3.3).


I can't find it explicit in the spec, but I'm assuming the reason is because it's expected to return an lvalue.

Scratch that: it didn't make sense. It returns an lvalue of the subscripted type not the object type.

Jeffery Thomas
  • 42,202
  • 8
  • 92
  • 117