Why we cannot overload subscript operator using friend function
CodePudding user response:
Not all operators can be overloaded. For those that can be overloaded there are rules whether they can be non-members or not. For details I refer you to https://en.cppreference.com/w/cpp/language/operators.
The operators that can be overloaded only as members are =
,()
,[]
and ->
.
CodePudding user response:
Let's add overloading to a language that is derived from C. Did you know that the built-in operator is symmetric? For raw arrays it's always true that a[i] == i[a]
. It's an emergent property that may be cute, but hardly conducive for great code.
So, wouldn't it be a good idea to limit our overloading to only have our "container object" on the left? Many will say yes. And it is also true that the left-hand side of an expression is always taken as this
for member lookup.
Now if we only want to allow the object on the lhs, the choice is easy: only allow defining the operator as a member. For a similar reason operator=
is a member-only operator too, because the object being assigned to only makes sense (to the language designer) on the left.