Why it is possible to overload operators [], (), ->, = only through class methods?
1 answer
Why not? It is even possible:
class Test { public: void operator[](int i) { cout << "[" << i << "]\n"; } void operator()(int i) { cout << "(" << i << ")\n"; } Test* operator->() { cout << "->"; return this; } void operator=(int i) { cout << "=" << i << "\n"; } int j = 5; }; int main(int argc, const char * argv[]) { Test t; t[0]; t(1); cout << t->j << endl; t=3; } Moreover, as far as I remember, these operators cannot be made free, but only by members.
But this is quite understandable - such an overload would make it possible to redefine the corresponding global operators, which is fraught from a security point of view.
In addition, based on semantics, for these operators the left-hand side cannot but be a reference to a class object, so there is not much point in a free operator — you must still write it with the first argument — a reference to a class object. And in the case of -> - return the pointer ... All these restrictions and lead to a restriction on the method of implementation.
"I think so" (c) Pooh
- Overload protection for global operators relies on types, so I don’t see any security issues here.
->not required to return a pointer, but must return something with which it can be used->again (for example, any smart pointer will do). - αλεχολυτ