views:

152

answers:

2

I'm trying something like this:

Foo & operator=(Foo & to, const Bar &from);

But I'm getting this error:

E2239 'operator =(Foo &, const Bar &)' must be a member function

Are there limitations on which operators can/cannot be defined as Free Functions, and if so, why?

+13  A: 

The assignment operator must be a non-static member function and must have exactly one parameter:

An assignment operator shall be implemented by a non-static member function with exactly one parameter (C++03 13.5.3/1).

operator(), operator[], and operator-> must also be implemented as non-static member functions.

Class-specific operator new and operator delete (and variants thereof) must be implemented as static member functions (note that these are implicitly static, even if they are not declared with the static keyword).

James McNellis
A: 

It cannot.

The reason, I guess, has to do with copy constructor. They have very similar semantics, and, you cannot define a copy constructor outside of a class just like other constructor. So, they didn't want to separate the twins far apart (to avoid the twins paradox:).

P.S. What's a shame in C++, is that you cannot add a member to existing class. There's no low-level reason for that. If it would be possible, you could decouple header and cpp dependencies by not declaring private functions in the class definition header.

Pavel Radzivilovsky
@Pavel: If what you are talking about is adding members after the class definition is complete, there certainly are reasons for that. You can't add virtual members later on because by the time the class definition is done the compiler MUST know how big the object (including vtable!) is. Adding non-virtual members outside the class definition would make 'private' pointless because anyone would be able to add members that examined/modified private data. In the context of C++ as a whole, it would break much of what they were trying to achieve.
Michael Kohne
Well, first could be good for adding public members. Second, more importantly, it would only require a "friend" or some kind of forward declaration in the class definition, which would help decouple dependencies.
Pavel Radzivilovsky