Reputation: 47
Basically, I have created a doubly linked list and now need to show that the destructor is implemented and tested back in main.cpp (int main).
It was suggested in the assignment that I should create a function, as well as to place a cout statement that outputs the address of each node right before it is deleted. I am not sure how I should go by doing this.
So far, I have created a function like this:
void cList() {
DoublyLinkedList a
cout << "ex: 0 1 2 3" << endl;
for (unsigned i = 0; i < 4; i++) {
a.push_back(i);
}
cout << "Display in function: ";
a.display();
cout << endl;
//this shows the addresses of each node
cout << "delete addresses: " << endl;
for (it = del.begin(); it!=del.end(); ++it) {
cout << &it << endl;
}
}
I understand that when the list is out of scope, the destructor will be called. I have a cout statement back in the ~DoublyLinkedList that says "destructor called". When I do this, the "destructor called" statement is outputted after the addresses are displayed. But how do I fulfill the requirement by displaying the address before it is deleted? Thank you.
Sample Output:
delete addresses:
0x7ffeb484d300
0x7ffeb484d300
0x7ffeb484d300
0x7ffeb484d300
Destructor Called
Upvotes: 1
Views: 896
Reputation: 1173
You can put this part into the destructor:
cout << "delete addresses: " << endl;
for (it = del.begin(); it!=del.end(); ++it) {
cout << &it << endl;
}
so the output of deleted nodes will be automatically shown when the function ends.
//This is assuming you aren't using any sentinel head/tail pointers.
~DoublyLinkedList() {
cout << "delete addresses: " << endl;
Node* nextNode = nullptr;
while(headPtr) {
nextNode = headPtr->next;
cout << headPtr << endl;
delete headPtr;
headPtr = nextNode;
}
cout << "Destructor Called" << endl;
}
Upvotes: 0
Reputation: 117856
Your constructor can output the object as it is created:
Node::Node()
{
std::cout << "Creating node: " << this << std::endl;
}
then your destructor can output the opposite as it is destroyed
Node::~Node()
{
std::cout << "Destroying node: " << this << std::endl;
}
Then you don't need to delete
anything in main. You just need to make sure your destructor for DoublyLinkedList
goes through and destroys all the Node
objects. Then when DoublyLinkedList a
falls out of scope you'll see your output from the destructors.
Upvotes: 3