class CList { public: struct list { char info[100]; struct list *next; }; struct list *head; CList(); CList(const CList &obj); ~CList(); }; 

Actually, how to make a copy constructor?

    2 answers 2

    It depends on what you want to receive. You can simply copy the head pointer - in this case it will be an object pointing to the same list.

    But if you want to completely copy the entire list - then you have to recursively go through the chain, i.e. create a copy of the list pointed to by head, set the head pointing to it, go to this list (eq you unsuccessfully called it! node would be much better). In it, if the original next not zero - repeat the same steps ...

    Like that. In fact, this is the difference between shallow and deep copying ...

    Update I would do something like this - the list constructor:

     struct list { char info[100]; struct list *next; list(const list& l) { memcpy(info,l.info,100); if (l.next == 0) next = 0; else next = new list(*l.next); } }; 

    and then the CList constructor would

     CList(const CList &obj) { if (obj.head == 0) head = 0; else head = new list(*obj.head); } 

    Not compiled, just outlined the idea.

    • For some reason, it seems that flat copies are usually obtained by mistake. Never had the task to make a flat copy. Only nakosyachit so. - Alexey Sarovsky
    • @ AlekseySarovsky Usually - yes, but exceptions only confirm the rule :) - Harry

    Something like this:

      // Harry подсказал, что это явно похоже на список head = new list(); list* current = head; list* forCopy = obj.head; while(forCopy != NULL) { current = new list(); memcpy(current, forCopy, sizeof(list)); forCopy = forCopy.next; current.next = new list(); current = current.next; } 
    • Poorly. This is not a shallow copy — you create a new list node, but not a deep one — you do not go further down the list. The result is, um ... unfinished. - Harry
    • Yes, I agree, I did not see right away that it looks like a list. - Alexey Sarovsky