Search code examples
c++operator-overloadingassignment-operator

Why cannot a non-member function be used for overloading the assignment operator?


The assignment operator can be overloaded using a member function but not a non-member friend function:

class Test
{
    int a;
public:
    Test(int x)
        :a(x)
    {}
    friend Test& operator=(Test &obj1, Test &obj2);
};

Test& operator=(Test &obj1, Test &obj2)//Not implemented fully. just for test.
{
    return obj1;
}

It causes this error:

error C2801: 'operator =' must be a non-static member

Why cannot a friend function be used for overloading the assignment operator? The compiler is allowing to overload other operators such as += and -= using friend. What's the inherent problem/limitation in supporting operator=?


Solution

  • Because the default operator= provided by the compiler (the memberwise copy one) would always take precedence. I.e. your friend operator= would never be called.

    EDIT: This answer is answering the

    Whats the inherent problem/limitation in supporting = operator ?

    portion of the question. The other answers here quote the portion of the standard that says you can't do it, but this is most likely why that portion of the standard was written that way.