@ne555
> copied the bits from the right hand side that was passed with the operator=
No, you never touched `other' in your code. |
Sorry it was late and I am still a noob in training.... but your are right I did not connect the pointer to other at all... Never noticed though so I thanks for pointing it out so that I can correct the glaring mistake in my new code.
[quote> (delete anything that is assigned to it if it exists)
¿what do you mean with `delete' ?][/quote]
What I meant with delete is say A and B are vectors of ints instead of my polynomial lists.
If:
A={9,8,7,6,5,4}
B={0,1,2,3}
And I copy B's contents over to A without deleting A I would end up with:
A={0,1,2,3,5,4} or at the very least A={0,1,2,3, , }
which means A!=B because of extra values or different capacity vectors depending on the copy implementation.
So first I need to destruct A if it declared and initialized to clear out anything stored in A so that A={}.
Then copy B's contents over to A so that A==B.
But this is a semantic exercise without some code to show so is this version better?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
|
// assignment operator
Polynomial& Polynomial::operator=(const Polynomial& other){
if(this==&other){
return *this;
}
PolyNode* temp;
for(PolyNode* current_ptr=firstTerm; current_ptr!=nullptr; current_ptr=temp){
temp=current_ptr->next;
delete current_ptr
}
firstTerm=nullptr; //not sure if this would be correct but I need "this" to be the head of the copied list where firstTerm==nullptr so set_coefficent works
for(PolyNode* current_ptr=other.firstTerm; current_ptr!=nullptr; current_ptr=current_ptr.next){
this->set_coefficient(current_ptr->coefficient, current_ptr->degree);
return *this;
}
|
Thanks again for the insights.