Deep Copy Constructor in a Linked List class

I am struggling to write a copy constructor for my linked list class.

I keep getting the following error:
LinkedList.cpp: In copy constructor âLinkedList::LinkedList(const LinkedList&)â:
LinkedList.cpp:22:23: error: passing âconst LinkedListâ as âthisâ argument of âNode* LinkedList::getHead()â discards qualifiers [-fpermissive]

I never made a "deep" copy constructor before, and I really have no idea what I'm doing.

Anyone see what's wrong?

Here's the constructor:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
LinkedList:: LinkedList(const LinkedList & List)
{
        Node * curr = List.getHead();//Error occurs here
        Student * sPtr;
        Node * newPtr;

        while (curr)
        {
                sPtr = new Student;
                if(!sPtr)// Error checking
                {
                        cerr << "Error: bad allocation";
                        exit(EXIT_FAILURE);
                }

                newPtr = new Node (sPtr);
                if(!newPtr) // Error checking
                {
                        cerr << "Error: bad allocation";
                        exit(EXIT_FAILURE);
                }

                sPtr -> setFname(curr -> get_sPtr() -> getFname());
                sPtr -> setMi(curr -> get_sPtr() -> getMi());
                sPtr -> setLname(curr -> get_sPtr() -> getLname());
                sPtr -> setSSN(curr -> get_sPtr() -> getSSN());
                sPtr -> setAge(curr -> get_sPtr() -> getAge());

                curr = curr -> getNext();

                insert(newPtr);
        }

//      Deep copy, head to tail

}
"Discards qualifier" usually means you called a non-read only member function. Your getHead function does not guarantee that the variables in the const variable List are not modified, thus breaking the const attribute of the variable.

Just make your getHead function read-only if it does not modify any variables.
1
2
3
4
5
6
7
//Function prototype
getHead()const; //const after the parameter parentheses makes the function read-only
                //i.e. the values can be retrieved but not modified
//Function definition
LinkedList::getHead()const{
   /*...*/
}
Topic archived. No new replies allowed.