What does "operator = must be a non-static member" mean?


Question

I'm in the process of creating a double-linked list, and have overloaded the operator= to make on list equal another:

template<class T>
void operator=(const list<T>& lst)
{
    clear();
    copy(lst);
    return;
}

but I get this error when I try to compile:

container_def.h(74) : error C2801: 'operator =' must be a non-static member

Also, if it helps, line 74 is the last line of the definition, with the "}".

1
23
2/19/2012 10:48:19 PM

Accepted Answer

Exactly what it says: operator overloads must be member functions. (declared inside the class)

template<class T>
void list<T>::operator=(const list<T>& rhs)
{
    ...
}

Also, it's probably a good idea to return the LHS from = so you can chain it (like a = b = c) - so make it list<T>& list<T>::operator=....

21
8/17/2019 1:24:54 PM

Put that operator inside your class definition. It must be a member because operator= is special and you would not gain something by writing it as a non-member anyway. A non-member operator has two important main benefits:

  • Implicit conversions of the right and the left side of the operator invocation
  • No need to know about internals of the class. Function can be realized as non-member non-friend.

For operator=, both is not usable. Assigning to a temporary result of a conversion does not make sense, and operator= will need access to internals in most cases. In addition, a special operator= is automatically provided by C++ if you don't provide one (the so-called copy-assignment operator). Making it possible to overload operator= as a non-member would have introduced additional complexity for apparently no practical gain, and so that isn't allowed.

So change your code so that it looks like this (this assumes the operator= is not a copy-assignment operator, but assigning from a list<T> to something else. This isn't clear from your question):

class MyClass {
...
    template<class T>
    MyClass& operator=(const list<T>& lst)
    {
        clear();
        copy(lst);
        return *this;
    }
...
};

It's pretty standard that a operator= returns a reference to itself again. I recommend you to adhere to that practice. It will look familiar to programmers and could cause surprises if it would return void all of a sudden.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon