Home > other >  Copy Constructor Error With a Template Linked List Class : no matching function for call to 'No
Copy Constructor Error With a Template Linked List Class : no matching function for call to 'No

Time:03-09

I'm trying to make a copy constructor for a linked list but I'm not sure how to fix this error and I've been looking for hours. The error is:

no matching function for call to 'Node::Node()'

Here is the code:

template <class T>
class Node      //node is the name of class, not specific
{
public:
    T data;     //t data allows for any type of variable
    Node *next;     //pointer to a node

    Node(T Data)    //assign data value
    {
        data = Data;    //makes data = NV parameter
        next = nullptr; //makes next = to nullptr
    }
};

template <class T>
class LinkedList
{
private:
    Node<T> * head, *tail;      //// typedef Node* head // -- head = Node* --   //// typedef Node* nodePtr =  Node* ////
public:
    LinkedList()        //constructor for Linked List
    {
        head =  nullptr;
        tail = nullptr;
    }

    LinkedList(LinkedList& copy)
    {
        head = nullptr;
        tail = nullptr;
        Node<T>* Curr = copy.head;


        while(Curr) //while not at end of list
               {
                   //val = copyHead->data;
                   Node<T>* newCpy = new Node<T>;
                   newCpy->data = Curr->data;
                   newCpy->next = nullptr;

                   if(head == nullptr)
                       {
                           head = tail = newCpy;
                       }
                   else
                       {
                           tail->next = newCpy;
                           tail = newCpy;
                       }

               }

    }
       ~LinkedList()
       {
           while (head)
            {
                Node<T>* tmp = head;
                head = head->next;
                delete(tmp);
            }
            head = nullptr;
       }

CodePudding user response:

The class Node does not have the default constructor. It has only the following constructor

Node(T Data)    //assign data value
{
    data = Data;    //makes data = NV parameter
    next = nullptr; //makes next = to nullptr
}

And in this statement

Node<T>* newCpy = new Node<T>;

there is used the default constructor that is absent.

At least instead of these three statements

//val = copyHead->data;
Node<T>* newCpy = new Node<T>;
newCpy->data = Curr->data;
newCpy->next = nullptr;

you need to write

//val = copyHead->data;
Node<T>* newCpy = new Node<T>( Curr->data );

Pay attention to that within the while loop

while(Curr)
{
    //...
}

the pointer Curr is not changed. So the loop is infinite if Curr is not a null pointer

It seems you forgot to insert this statement

Curr = Curr->next;

before the closing brace of the loop.

  • Related