Reputation: 71
I have the following copy constructor made for a Polynomial class. The constructor is supposed to create an independent deep copy of the input Polynomial object. Is the copy constructor actually doing this or is it creating a shallow copy?
Polynomial::Polynomial(const Polynomial &p) {
cout << "Enter method\n";
if(p.head != NULL) {
cout << "Enter if\n";
Node* n = p.head;
int nDegree = n->degree;
while(n != NULL) {
this->add(n->coeff, n->degree);
nDegree--;
n = n->next;
}
n = NULL;
}
}
Here is the add method:
void Polynomial::add(const float& coeff, const int& degree) {
Node *temp = new Node(coeff, degree, NULL, NULL);
temp->coeff = coeff;
temp->degree = degree;
if(tail == NULL) {
head = temp;
tail = temp;
arrSize++;
}
else {
temp->prev = tail;
tail->next = temp;
tail = temp;
arrSize++;
}
}
Upvotes: 0
Views: 296
Reputation: 73456
Polynomial::add()
creates a new node and inserts it in a linked list.
Your copy constructor iterates through the existing linked list to add notes to the list being consutructed.
So it's a deep copy and not a shallow copy.
Remarks:
Consider initializing explicitey head
an tail
to NULL
in your copy constructor, before starting to add nodes.
Depending on the Node
constructor, apparently using coeff
and degree
you may consider not to redundantly reassign these values to temp
members.
The purpose of nDegree--;
in your loop is not completely clear to me. I think you could drop it.
Upvotes: 1