How to make implementation of assignment operator, please help.//Copy Constructo
ID: 3855992 • Letter: H
Question
How to make implementation of assignment operator, please help.//Copy Constructor: Make DEEP copy SortListClass::SortListClass(const SortListClass& existingList): size(existingList.size) {if (existingList.head -= NULL) head = NULL;//original list is empty else {//copy first node head = new SortListNode; assert (head != NULL);//check allocation head rightarrow item existingList.head rightarrow item;//copy rest of list SortListNode *newPtr - head;//new list pointer//newPtr points to last node in new list//origPtr points to nodes in original list for (SortListNode *origPtr existingList.head rightarrow next; origPtr ! = NULL; origPtr = origPir rightarrow next) {newPtr rightarrow next = new SortListNode;//link new node to end of list assert(newPtr rightarrow next; = NULL); newPtr = newPtr rightarrow next; newPtr rightarrow item = origPtr rightarrow item;//copy the data newPtr rightarrow next = NULL;}}//retum(*this);}/*//assignment operator Make DEEPcopy SortListClass& SortListClass::operator=(const SortListClass& rhs) {//TODO//Similar to Copy Constructor, except//- Avoid self-assignments such as "X = X;"//- Delete existing this-instance content before//making this-instance a copy of the rhs instance return(*this);}Explanation / Answer
//assignment operator:Make Deep copy
SortedList& SortedList::operator=(const SortedList rhs){
// first existing head
delete head;
//copy first node
head = new SortedListNode;
assert(head != NULL);
head->item = rhs.head->item;
//copy all items
SortedList* newPtr = head;
for(SortedList* origPtr=rhs.head->next; origPtr != NULL; origPtr = origPtr->next;){
newPtr->next = new SortedList;
assert(newPtr->next != NULL);
newPtr = newPtr->next;
newPtr->item = origPtr-item;
newPtr->next = NULL;
}
return *this;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.