I'm having trouble wrapping my head around the concept of an assignment operator, or at least creating them successfully.
Copy Constructors aren't an issue for me; here is mine that its working:
//copy constructor
Set::Set(const Set &rhs){
_head = rhs._head;
_tail = rhs._tail;
//null, basically this object is 0
if(rhs._head == NULL){
_head = NULL;
_tail = NULL;
_size = 0;
}else{
_head = new Elem(*rhs._head);
_tail = new Elem(*rhs._tail);
_size = rhs._size;
Elem *prev = NULL;
Elem *curr = _head;
Elem *otherCurr = rhs._head;
int counter = 0;
while(otherCurr->next != NULL){
curr->next = new Elem(*otherCurr->next);
curr->next->prev = curr;
curr = curr->next;
otherCurr = otherCurr->next;
}
//now that we are done lets setup the tail
_tail->prev = curr;
curr->next = _tail;
}
}
I was reading example code, and saw some people used the #include <algorithm>
library to implement it. I tried that instead, however does not seem to work at all.
//assignment operator
Set& Set::operator=(const Set &rhs){
Set temp(rhs);
std::swap(temp._head,_head);
std::swap(temp._tail, _tail);
return *this;
}
This above code however does not work correctly. Really struggling to grasp the concept of how assignment operators are made. I figured it would basically work the same as you want to copy values from one into another. But evidently not. If anyone could advise me on how to get that working it would be great.
Just some more general info on my class, there is a _head
and a _tail
that points to the start and end of the list. Dummy Elements.
Here is how the object is structured:
struct Elem {
ELEMENT_TYPE info;
Elem *prev, *next;
};
Elem *_head, *_tail;
int _size;
See Question&Answers more detail:os