0

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;
        }
    }
}
Mat
  • 45
  • 2
  • 10
  • first, it seems to me that you initialize a reference with a pointer, don't you? – undermind Feb 11 '15 at 17:21
  • 1
    The function is delcared to return a LinkedList&, but your code returns a LinkedList*. There's a type mismatch, so the compiler barfs at you about it. – thang Feb 11 '15 at 17:21

1 Answers1

2

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.

Matt
  • 6,010
  • 25
  • 36
  • Thanks. The thing is just, we may not alter the header file (so we may not change the function prototype) – Mat Feb 11 '15 at 17:25
  • @Mat The thing is.. that thing isn't relevant. This is the correct fix (barring smart pointers and RAII modeling, which is really the *right* way to do this). The instructor that provided that header to you leaves but-one option for properly cleaning up that dynamic allocation (`delete &refvar;`) and that option leaves open a massive whole of a memory leak if used incorrectly, which would be an easy mistake. Maybe the author of that header should be sitting on the other side off the classroom. – WhozCraig Feb 11 '15 at 17:32
  • 1
    Whoever wrote that header is an idiot. http://stackoverflow.com/questions/752658/is-the-practice-of-returning-a-c-reference-variable-evil – thang Feb 11 '15 at 17:33