Search code examples
c++linked-listoverloadingassignment-operator

Assignment operator linked list c++


I am attempting to code an assignment operator for a linked list class in c++. The errors I'm getting say that "head" is undeclared, but I'm not sure where I'm supposed to declare it. It's being used in other functions without a problem. Another error says my use of "this" is invalid.

template <class T>
SortedLinkList<T>& operator=(const SortedLinkList<T> & otherList)
{
    if(&otherList != this) {
        Node<T> temp = head;
        while(temp->getNext() != NULL) {
            head = head -> getNext();
            delete temp;
            temp = head;
        }
        count = 0;

        temp = otherList.head;
        while(temp != NULL) {
            insert(temp);
        }
    }
    return *this;
}

Solution

  • The this pointer is unavailable because your function signature does not resemble a member definition, you're missing the type scope resolution part of the signature:

    template <class T>
    SortedLinkList<T>& operator=(const SortedLinkList<T> & otherList)
    

    should be:

    template <class T>
    SortedLinkList<T>& SortedLinkList<T>::operator=(const SortedLinkList<T> & otherList)