Question

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?

Was it helpful?

Solution

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).

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top