#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Apr 2013
    Posts
    20
    Rep Power
    0

    Copy constructor for a linked list


    I am trying to create a copy constructor for a linked list and am wondering if this is correct or not.

    Code:
    //copy constructor
    list::list(const list &list){
    	//headByName = list.headByName;
    	//headByRating = list.headByRating;
    	 
    	node* tempPtrByName = list.headByName;
    	node* tempPtrByRating = list.headByRating;
    
    	while (tempPtrByName){
    		insert(tempPtrByName->item);
    		tempPtrByName = tempPtrByName->nextByName;
    	}//end by name while loop
    	while (tempPtrByRating){
    		insert(tempPtrByRating->item);
    		tempPtrByRating = tempPtrByRating->nextByRating;
    	}//end by rating while loop
    }//end copy constructor
  2. #2
  3. Contributing User
    Devshed Supreme Being (6500+ posts)

    Join Date
    Jan 2003
    Location
    USA
    Posts
    7,145
    Rep Power
    2222
    I think we would need to see insert() as well in order to see what it does.

    I assume that you are wanting to do a deep copy rather than a shallow copy (see Wikipedia: http://en.wikipedia.org/wiki/Deep_co...ods_of_copying). IOW, that you want the resultant list to be a complete duplicate of the original but without pointing to any of the same data. IOW, you don't just copy a pointer, but rather you create a copy of what that pointer was pointing at and then set the pointer field to that copy.

    I also assume that insert() works by first searching the other listhead's list (if that listhead != NULL) for a match. If there's a match then it fixes the pointers, but if there's not a match then it inserts it into the list.

    Now that I look at it again, it's not going to do a deep copy. For a deep copy, you would need first to create a copy of tempPtrByName->item, copy the data fields into that copy and initialize the pointer fields appropriately, and then pass that copy to insert(). At least the constructor as it is doesn't do a deep copy unless insert() does that creation of a copy of item.

    ABE: IOW, you would need to new a new node using node's copy constructor and pass that copy to insert(). In pre-1998 C++ a struct was a kind of a class and could take constructors and a destructor; I very much doubt that that has changed in the new C++ standard.
    Last edited by dwise1_aol; April 18th, 2013 at 07:07 PM.
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Apr 2013
    Posts
    20
    Rep Power
    0
    Thanks again I got the copy constructor all setup with your advice. I appreciate your time and help.

IMN logo majestic logo threadwatch logo seochat tools logo