Mat
Mat

Reputation: 45

"invalid initialization of non-const reference of type..." Error in clone() function

Good day

I am busy to implement linear data structure in c++. I am struggeling with my clone() function. The one line code seems in order for me, but maybe the error is in the copy constructor. The error I am getting: linkedList.C:22:32: error: invalid initialization of non-const reference of type ‘LinkedList&’ from an rvalue of type ‘LinkedList*’ return new LinkedList(*this);

template<class T>
LinkedList<T>& LinkedList<T>::clone()
{
    return new LinkedList<T>(*this);
}

template<class T>
LinkedList<T>::LinkedList(const LinkedList<T>& other)
{

    Node<T>* newNode;
    Node<T>* current;
    Node<T>* trailCurrent;

    if(head != NULL)
        clear();
    if(other.head == NULL)
        head = NULL;
    else
    {
        current = other.head;
        head = new Node<T>(current->element);
        head->next = NULL;

        trailCurrent = head;
        current = current->next;

        while(current != NULL)
        {
            newNode = new Node<T>(current->element);
            trailCurrent->next = newNode;

            trailCurrent = current;
            current = current->next;
        }
    }
}

Upvotes: 0

Views: 183

Answers (1)

Matt
Matt

Reputation: 6050

You can change your clone function to:

template<class T>
LinkedList<T>* LinkedList<T>::clone()
{
    return new LinkedList<T>(*this);
}

Remember to free the memory after calling the clone function.

Upvotes: 2

Related Questions