My copy constructor is referring to another address instead of copying the values, can you guys please find the problem for me?
This is the copy constructor:
Poly::Poly(const Poly& copyList)
{
// copy the first term
power = copyList.power;
coef = copyList.coef;
if (copyList.nextTerm == NULL)
{
nextTerm = NULL;
}
else
{
// copy the next term
PolyPtr trackCopy = copyList.nextTerm;
nextTerm = new Poly;
PolyPtr trackOriginal = nextTerm;
PolyPtr newTerm;
while (trackCopy != NULL)
{
newTerm = new Poly;
newTerm->coef = trackCopy->coef;
newTerm->power = trackCopy->power;
trackOriginal->nextTerm = newTerm;
trackOriginal = newTerm;
trackCopy = trackCopy->nextTerm;
}
}
}
copyList here is a class with private member variables as coef, power and a nextTerm that refers to the next node of the list
Here are is the interface of Poly:
class Poly
{
public:
// constructors
Poly();
Poly(int constant);
Poly(int coef, int power);
Poly(const Poly& copyList);
// set functions
void setPower(int number);
void setCoef(int number);
void setNextTerm(Poly* link);
// member function to compute
int evaluate(int x);
private:
int power;
int coef;
Poly* nextTerm;
};
typedef Poly* PolyPtr;
An example is here:
int main()
{
PolyPtr polyNomial = new Poly(2, 3);
PolyPtr nextTerm = new Poly(5, 8);
polyNomial->setNextTerm(nextTerm);
PolyPtr copyTerm(polyNomial);
PolyPtr newTerm = new Poly(1, 2);
copyTerm->setNextTerm(newTerm);
cout << copyTerm->evaluate(3) << endl;
cout << polyNomial->evaluate(3) << endl;
return 0;
}
Here I expected the evaluation of the copyTerm and polyNomial to be different but they are the same