inherit
27278
0
Aug 3, 2024 9:13:18 GMT -8
Josh
Apple iManiac / eBay Addict
12,347
July 2004
jwd41190
|
Post by Josh on Sept 21, 2010 11:48:14 GMT -8
Hello,
I am trying to make a copy constructor for my code below, but not sure how to go about starting it off.
[Done]
Also do I need to to create a new cpp file for my copy constructor or can I do it in the same one? We were only given a cpp file not a header file. Thanks
|
|
#00AF33
14306
0
1
Sept 8, 2023 8:54:17 GMT -8
Jordan
What is truth?
11,838
October 2003
jab2
|
Post by Jordan on Sept 21, 2010 20:21:28 GMT -8
The purpose of a user defined copy constructor is to copy another object which has dynamic memory. In other words, to perform a deep copy of the object. The compiler actually automatically creates a default constructor, a copy constructor and a operator= function for you, but in the cases where you have memory allocated on the heap these functions would just copy the pointers and the addresses they point to instead of the actual data.
In this case you just need to traverse through the list and allocate a new node for each node that you encounter.
Here's some code, but it's not tested. Be sure to always pass the object to copy by reference because if you don't the copy constructor itself would be called which you can see is a problem because it's calling itself. That would cause an infinite loop.
LList::LList(const LList &list) { head = NULL;
// Get the address of the other list's head. node* temp = list.head;
// Traverse through the list and copy each node. while(temp) { insert(temp.data); temp = temp->next; } }
And you can put the copy constructor in either the header file or in the implementation file. It does not matter.
|
|
inherit
27278
0
Aug 3, 2024 9:13:18 GMT -8
Josh
Apple iManiac / eBay Addict
12,347
July 2004
jwd41190
|
Post by Josh on Sept 22, 2010 12:18:46 GMT -8
Ok, thanks I got it figured out now...
|
|