Search code examples
c++operator-overloadingassignment-operator

C++ - On friend assignment-operator overloads


I’ve been experimenting with creating code interfaces with C++ classes.

And a puzzling thing that came up in testing is overloading assignment operators. Take a look at the code below:

struct my_object {
  // This doesn't work. :(
  friend int& operator =(int& variable, my_object object)
  { variable = object.value; return variable; }

  // This works, but `int value; value <<= my_object{};` 
  // for `int value; value = my_object{};` doesn't seem clean...
  friend int& operator <<=(int& variable, my_object object)
  { variable = object.value; return variable; }
};

My confusion is:
The first overload does not compile and logs this error to the console terminal.

'friend int& operator =(int&, my_object)' must be a nonstatic member function

But then, the second overload compiles with no errors (or warnings) whatsoever despite being near identical to the first one.


Why is the first operator overload invalid and the second one seemingly fine (at least by the GCC 6.3.0 compiler)?


Solution

  • The =, () (function call), and [] operators are required to be members of the class. Other operators generally are allowed to be either members or non-members.

    It follows that the only time when you can overload the assignment operator is when defining the class on the left-hand side. There is no way to write a custom assignment operator whose left-hand argument is a non-class type.

    In order to assign my_object to int, you need to write a conversion function instead:

    struct my_object {
        operator int() const { return value; }
        // ...
        int value;
    };