views:

185

answers:

2

The operators are = () [] -> ->* conversion operators

These can be declared only as member functions.

Any other operator function can be either a class member or a non-member function.

What is the rationale for this restriction?

+4  A: 

The rationale is that it would not make sense for them to be non-members, as the thing on the left-hand side of the operator must be a class instance.

For example, assuming a class A

A a1;
..
a1 = 42;

The last statement is really a call like this:

a1.operator=(42);

It would not make sense for the thing on the LHS of the . not to be an instance of A, and so the function must be a member.

anon
Steve Jessop
Well, it doesn't really matter if I haven't made the case against - we have to accept what the standard says. And of course you can do (almost) anything you like via a named friend function.
anon
Tim Sylvester
"we have to accept what the standard says" - of course, but that does not exclude seeking a rationale. Usually, the committee made decisions for a reason. You've said the reason this is forbidden is that it "doesn't make sense". As opposed to, say, because some committee member slipped it into the standard while drunk ;-)
Steve Jessop
@onebyone Sorry, I have no more access than you to the mind-states of standard comittee members. But I believe what I said in the answer is more or less the rationale. It strikes me that your proposal wouldn't work because the thing that becomes the LHS would be a temporary.
anon
Steve Jessop
+4  A: 

Because you can't modify the semantics of primitive types. It wouldn't make sense to define how operator= works on an int, how to deference a pointer, or how an array access works.

eduffy