Good day! I am making a program that simulates a Polynomial using a linked-list. So I have two classes: Term and Poly. The Term class has three private attributes and those are: int coef, int exp, and Term *next. The Poly Class has only one attribute and that is for the header node which is declared as Term *header. I tried to override the operator "=" so that I could do like this:
Poly p1; //creates a header note; basically this is an empty linkedlist
p1.addTerm(4, 5); //adds a term to the polynomial
Poly p2;
p2 = p1; //deletes/clears all the contents of p2 and makes a copy of all the contents of p1
The addTerm function works fine, so as the constructor. I guess the problem is the overriding of the "=" operator. So here is my code:
Poly Poly::operator =(const Poly &source) {
clearPoly();
Term *t = header;
Term *s = source.header->getNext();
while(s != NULL) {
t->setNext(new Term(s->getCoef(), s->getExp()));
t = t->getNext();
s = s->getNext();
}
return *this;}
Please help me :( By the way, if something's not clear from my question, please do tell me.
ADDITIONAL FINDINGS
After trying to debug, I've narrowed down the problem. So here's what I found out. I tried to edit my implementation of the operator =. Here it is
Poly Poly::operator =(const Poly &source) {
clearPoly();
Term *t = header;
Term *s = source.header->getNext();
while(s != NULL) {
t->setNext(new Term(s->getCoef(), s->getExp()));
t = t->getNext();
s = s->getNext();
}
display();
return *this;
}
The display function inside the implementation displays the desired output. However, in the main, the display function outputs unwanted/garbage values.
RESULT OF DISPLAY FUNCTION INSIDE THE IMPLEMENTATION
5x^6 3x^5 1x^1
RESULT OF DISPLAY FUNCTION IN MAIN
5574864x^5570756 5575824x^5575896 5598264x^5574864
Any idea on how that misbehaved?