I am working on a C++ project that works with polynomials stored in a LinkedList. I want to overload important operators such as +, -, *, /. I had some issues with destructor when the function returns the result.
Polynomial& Polynomial::operator+(const Polynomial &p){
Polynomial sum = *this;
if (p.list.isEmpty())
return *this;
ListElement *temp = p.list.first;
while (temp){
sum.list.addSorted(temp->data);
temp = temp->next;
}
return sum;
}
This function works very good, but return sum;
calls the destructor and I lose the data. The destructor from Polynomial class calls list.purge();
which frees the dynamic memory in linked list. All the classes and its methods are good.
In main I have:
Polynomial p1,p2,sum;
p1.input(); //here I input data for first pol
p2.input();
sum=p1+p2; //I overloaded operator=, it works fine
What I must do "to stop" the destructor? I want to output on screen Polynomial sum
. Thank you!