Why can overloaded operators not be defined as static members of a class?

Because there isn’t an obvious syntax to call such an operator, which would mean we’d have to make up something. Consider the following variables:

X x1;
X x2;

Now, let’s pretend for a moment that we’re using normal member functions instead of operators – let’s say I changed operator+ to plus in your example.

Each of the three calls would look like:

x1.plus(x2);
plus(x1, x2);
X::plus(x1, x2);

Now when making an operator call using + how would the compiler know to look up your operator in the scope of X? It can’t do it for normal static member functions, and operators aren’t given special dispensation to disambiguate.

Now consider if you had both the second and third forms declared in your program. If you said x1 + x2 the compiler would either have to always pick the free function or the call would be ambiguous. The only real alternative would be something like x1 X::+ x2 which just looks ugly. Given all that, I’m sure the standards committee decided to simply forbid the static member version since anything it could accomplish could be done with a friend free function instead.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)