class - C++: Copy constructor is deleting nodes in original object -
i have implemented singly linked list using template class , attempted create working copy constructor. when copy constructor called, accurately duplicates list. however, deletes nodes original.
here class implementation, constructors, , destructors:
template<class l> class linkedlist { public: linkedlist(); linkedlist(const linkedlist<l> &og); ~linkedlist(); node<l>* addtoend(l object); node<l>* addtomiddle(l object); node<l>* deletenode(l deleteitem); node<l>* reverselist(); void display(); int size(); private: node<l>* head; node<l>* tail; int size; }; template<class l> linkedlist<l>::linkedlist() { head = null; tail = null; size = 0; } template<class l> linkedlist<l>::linkedlist(const linkedlist<l> &og) { cout << "\ncopy constructor has been called.\n\n"; head = new node<l>; *head = *og.head; tail = new node<l>; *tail = *og.tail; size = og.size; } template<class l> linkedlist<l>::~linkedlist() { delete head; delete tail; }
and main.cpp:
#include "header.h" int main() { int int1 = 1; int int2 = 2; int int3 = 3; int int4 = 4; int int5 = 5; cout << "creating first integer list..." << endl; linkedlist<int> intlist1; intlist1.addtoend(int1); intlist1.addtoend(int2); intlist1.addtoend(int3); intlist1.addtoend(int4); intlist1.addtoend(int5); intlist1.display(); cout << endl << "cloning , reversing..." << endl; linkedlist<int> intlist2(intlist1); intlist2.reverselist(); cout << "original list: " << endl; intlist1.display(); cout << "reversed list: " << endl; intlist2.display(); return 0; }
the output looks this:
creating first integer list... 1 2 3 4 5
cloning , reversing...
copy constructor has been called.
original list: 1 2 1 reversed list: 5 4 3 2 1
your copy constructor totally wrong. should iterate through linked list , copy each element of list. tail should point last element of list. code this.
template<class l> linkedlist<l>::linkedlist(const linkedlist<l> &og) { cout << "\ncopy constructor has been called.\n\n"; head = new node<l>; *head = *og.head; node *p = og.head->next; node *i = head; while (p != null) { i->next = new node<l>; *(i->next) = *p; p = p->next; = i->next; } tail = i; size = og.size; }
Comments
Post a Comment