Can C++ assignment operators be free functions?

Roddy picture Roddy · Jun 21, 2010 · Viewed 8k times · Source

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?

Answer

James McNellis picture James McNellis · Jun 21, 2010

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