Reputation: 39
I'm writing my node and list classes and everything works fine except when I include destructor , copy constructor and the assignment operator functions in the list class, and I don't know what is wrong with them or what I have miss not to include.
linklist::linklist()
:firstNode(NULL),
lastNode(NULL),
nodeCount(0) {}
linklist::~linklist()// destructor
{
node* current = firstNode;
while( current != 0 ) {
node* temp = current->getNextNode();
delete current;
current = temp;
}
firstNode = 0;
}
linklist::linklist(linklist &L)// copy constructor
{
firstNode = NULL;
nodeCount = 0;
node* temp = L.firstNode;
for(int i = 0; i < L.getNodeCount(); i++)
{
push_back(temp);
temp = temp->getNextNode();
}
}
linklist& linklist::operator=(const linklist& L)// overloading assignemnt operator
{
linklist* LL;
node* temp = L.firstNode;
while( temp != NULL ) {
LL->getLast();
temp = temp -> getNextNode();
}
return *LL;
}
Upvotes: 0
Views: 706
Reputation: 1002
You seem to have two issues. First, the destructor deletes all node structures. Any new linked list that copied using the copy constructor would have incorrect data once the original is destroyed. Second, it's probably better if you copied the node structure using its copy constructor. It's hard to say without exact information, but your linked list ctor could look something like:
firstNode = NULL;
nodeCount = 0;
node* temp = L.firstNode;
for(int i = 0; i < L.getNodeCount(); i++)
{
push_back(new node(*temp));
temp = temp->getNextNode();
}
This way the new linked list has its own copy of nodes.
Upvotes: 0
Reputation: 5998
Your assignment should be similar to your copy constructor. Because they both do almost the same thing.
The difference being you assignment should clear
what it in the list(itself) before starting copying the rhs(the other one).
And then it should return a reference to itself. return *this
. So that assignments can be chained.
linklist& linklist::operator=(const linklist& L)// overloading assignemnt operator
{
// Check if self assignment
if (&L == this)
return *this;
// clear myself.
// copy other.
return *this;
}
Upvotes: 1