Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can C++ assignment operators be free functions?

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?

like image 721
Roddy Avatar asked Jun 21 '10 20:06

Roddy


People also ask

Which Cannot be used as assignment operator?

Which of the following is not an assignment operator? Explanation: Assignment operators are used to assign some value to a data object. <= operator is used to assign values to a SIGNAL. := operator is used to assign values to VARIABLE, CONSTANTS and GENERICS; this operator is also used for assigning initial values.

What is correct about assignment operator in C?

An assignment operation assigns the value of the right-hand operand to the storage location named by the left-hand operand. Therefore, the left-hand operand of an assignment operation must be a modifiable l-value. After the assignment, an assignment expression has the value of the left operand but is not an l-value.

What is the function of assignment operator?

The assignment operator = assigns the value of its right-hand operand to a variable, a property, or an indexer element given by its left-hand operand. The result of an assignment expression is the value assigned to the left-hand operand.


1 Answers

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

like image 148
James McNellis Avatar answered Nov 16 '22 02:11

James McNellis