Sorry if there is bad formatting, but this is my first post. I am trying to use a copy constructor to copy the list in LinkedList and then show that they are the same in the copy using the display() function. My problem is that when I try to populate the object copy, it returns the error

passing ‘const LinkedList’ as ‘this’ argument discards qualifiers [-fpermissive]
       copy.add(nodePtr->value);

The header file:

class LinkedList
{
 protected:
  struct ListNode
  {
    double value;
    ListNode *next;
    ListNode(double valOne, ListNode *nextOne = nullptr)
    {
      value = valOne;
      next = nextOne;
    }
  };
  ListNode *head;
 public:
  LinkedList();
  LinkedList(const LinkedList &copy);
  void display();
};

The implementation file:

#include "linkedList.h"

LinkedList::LinkedList()
{
  head = nullptr;
  cout << "Linked List Created" << endl;
}

LinkedList::LinkedList(const LinkedList &copy)
{
  ListNode *nodePtr = head;
  while(nodePtr)
    {
      copy.add(nodePtr->value);
      nodePtr = nodePtr->next;
    }
}

void LinkedList::display()
{
  ListNode *nodePtr = head;
  while(nodePtr != nullptr)
    {
      cout << nodePtr->value << "  ";
      nodePtr = nodePtr->next;
    }
}

The instantiation file:

#include "linkedList.h"

int main()
{
  LinkedList variable;

  variable.add(1.1);
  variable.add(3.1);
  variable.add(10.32);

  variable.display();

  LinkedList copy(variable);
  copy.display();

  return 0;
}

What would be the correct implementation of the copy constructor?

It appears to me that you have the wrong idea about what a copy constructor is supposed to be doing. The present LinkedList should be constructed by copying the values in the passed LinkedList. In this instance head should start off as a new ListNode and the loop should iterate over copy to add the values to head. You currently have it the other way around

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.