I'm very new to pointers and linked lists, so please bear with me here. Each Polynomial object contains a linked list, and each Node of that list contains a coefficient (long), a degree (unsigned int), and a next pointer (Node). This overloaded operator must create a deep copy of the list:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
Polynomial& Polynomial::operator=(const Polynomial& p)
{
//Temporary nodes so the actual head pointers don't get changed.
Node *host = m_head;
Node *param = p.m_head;
//Traverse the list
while (param->m_next != NULL)
{
//Make deep copies.
host->m_coefficient = newlong(param->m_coefficient); //errors occur here
host->m_degree = newunsignedint(param->m_degree); //and here
host = host->m_next;
param = param->m_next;
}
return *this;
}
This compiles with the following errors:
Polynomial.cpp:89: error: invalid conversion from ‘long int*’ to ‘long int’
Polynomial.cpp:90: error: invalid conversion from ‘unsigned int*’ to ‘unsigned int’
I have two questions. Why is the error occurring, and is this the correct way to traverse a linked list?
A new expression results in a pointer. You can't implicitly convert a pointer to the pointed-to type (and since that isn't actually what you want, thank your compiler for not letting you do it. ;)
...is this the correct way to traverse a linked list?
You're traversing the lists fine. Copying, on the other hand... not so much. The simplest way to do this is to create a new list with p's content. Destroy the old list. Set head to point to the new list.
I have a destructor that deletes all nodes in the list. To destroy a specific list, do I have to call the destructor explicitly?
For the immediate future, you should never call a destructor explicitly. (There are reasons to do so when you're micomanaging memory, but you're unlikely to stumble onto them at your level of expertise.)
Your destructor is for destroying a Polynomial object. We aren't doing that, so the destructor isn't an appropriate function to call anyway. If, by chance, your destructor calls another function that destroys your linked list, it may be appropriate to call that function directly.
My destructor is actually part of the Node class. Polynomial contains a linked list of nodes, so Polynomial itself doesn't have a constructor. I'm guessing I should just stick to "delete"? I could just go through the linked list and delete all the nodes, but since my Node destructor already does that I was just looking for a way to type less.