In an effort to become a more competent C++ programmer I'm experimenting w/ using references. In the past I have usually used pointers when referring to objects, as you would for example in Objective-C.
So I've been programming a Polynomial class that stores a list of Term objects
(TermNode* termHead,termTail)
But when I try to add a term to the list using the first implementation listed, calling the constructor on Term in add term, overwrites the Term& reference in the previously created Term node, as if it used the this pointer from the previous invocation of the constructor.
What is technically wrong about the first implementation listed, that causes it to behave so abnormally? It just works when I use pointers and new even though I do not change the structure of TermNode.
struct TermNode {
Term& value;
TermNode* next;
};
Term::Term(int coefficient,int firstTermDegrees,int secondTermDegrees) {
this->coefficient = coefficient;
this->xDegree = firstTermDegrees;
this->yDegree = secondTermDegrees;
}
//Doesn't work
void Polynomial::addTerm(int coefficient, int xDegree, int yDegree) {
Term term(coefficient,xDegree,yDegree);
addTerm(term);
}
void Polynomial::addTerm(Term& term) {
TermNode* t = new TermNode{term,nullptr};
if(isEmpty())
{
termHead = t;
termTail = t;
}
else
{
termTail->next = t;
termTail = termTail->next;
}
}
//Does work
void Polynomial::addTerm(int coefficient, int xDegree, int yDegree) {
Term* term = new Term(coefficient,xDegree,yDegree);
addTerm(term);
}
void Polynomial::addTerm(Term* term) {
TermNode* t = new TermNode{*term,nullptr};
if(isEmpty())
{
termHead = t;
termTail = t;
}
else
{
termTail->next = t;
termTail = termTail->next;
}
}
bool isEmpty() {
return nullptr == termHead;
}