I am attempting to copy the entire linked list in my copy constructor, however I continue to get access Why isn't my copy construction working properly? errors:
Unhandled exception at 0x00AE506C in program.exe: 0xC0000005: Access violation reading location 0x00000004.
copy constructor
NodeSLList::NodeSLList(NodeSLList & list)
{
head = list.head;
IntNode *tmp = head;
cout << "copy constructor called" << endl;
int size;
size = list.GetSize();
for (int i = 1; i <= size; i++)
{
tmp->data= list.RetrieveNode(i).data;
tmp->next = list.RetrieveNode(i).next;
tmp = tmp->next;
}
}
in main
NodeSLList list2 (list1);
cout << "cout << list2 " << endl;
cout << list2 << endl;
The error occurs at cout << list2 << endl;
since the cop constructor did not properly copy the linked list.
One problem is this:
head = list.head;
IntNode *tmp = head;
You should not be copying pointer values. You will wind up with two pointers pointing to the same memory. Both objects should have different head
values.
If you have a function that adds a node to your linked list, then you can use it in the copy constructor to avoid this. Here is an example:
NodeSLList::NodeSLList(const NodeSLList & list) : head(0)
{
int size;
size = list.GetSize();
for (int i = 1; i <= size; i++)
addData(list.RetrieveNode(i).data);
}
This requires that you have a function similar to addData
that adds a new node using the data passed in. Note that this tests your addData
function to ensure it works properly. The copy constructor just calls it in a loop.
Finally, you also need an assignment operator to go along with the copy constructor (and also a destructor). The assignment operator can be written using the copy constructor and destructor as helper functions (i.e. the copy/swap
idiom).
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments