edit: I have now fixed the issue, I was stupidly deleting the whole bag in my overloaded operator and then trying to insert value into it. I wrote a function to clear the bag without deleting it, and now it works perfectly. Thank you everyone for your help. The original is as follows, in case anyone else ever finds his or herself making the same mistake:
I've seen a lot of other beginners having problems chaining an overloaded = operator, and their problem is almost always forgetting to return a reference in their overloaded operator. However, I believe I am doing so but I am still unable to correctly chain my overloaded + operator.
For example, if I create two MagicBags, mb1 and mb2, then I set
mb1 = mb2;
this compiles and runs correctly. When I then create a third MagicBag, mb3,
mb3 = mb2 = mb1;
won't compile, and I get a null pointer in my overloaded operator.
Here is my operator:
MagicBag& operator=(const MagicBag& other) {
if (this == &other) {
return *this;
}
this->~MagicBag();//clear calling bag
node<T> * a;//construct a temp node pointer to use as an iterator to loop over original bag and copy its contents
int tempSize = other.size - 1;
while (tempSize >= 0) {
a = other.first;
for (int i = 0; i < tempSize; i++) {
a = a->next;//get my null pointer here
}
tempSize--;
insert(a->value);
}
return *this;
}
the destructor is
~MagicBag() {
if (first == NULL)
return;
if (first->next == NULL) {
delete(first);
first = NULL;
return;
}
node<T> * a = first->next;
while (a != NULL) {
delete(first);
first = a;
a = a->next;
}
delete(first);
first = NULL;
}
and the insert function is your standard 4 line insert, I doubt that's the issue. What am I doing wrong? I believe my destructor is not the problem, however I am a beginner so it very well may be, and I also believe I am correctly returning a reference in my overloaded operator. In this commonly cited post, I seem to be following the standard convention for overloading so I'm confused why this works correctly once, but not when chained. I also saw in the linked article from that post, that it's unnecessary to check if the two arguments are the same, however removing that bit doesn't solve the problem. What have I done wrong here?