#Do you need to write a destructor for a Node class used in linkedlists?

26 messages · Page 1 of 1 (latest)

delicate prism
#

If so what should it even do? Here's my definitions of the node and linkedlist classes and how I wrote my linkedlist destructor

snow lagoonBOT
#

When your question is answered use !solved to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question run !howto ask.

delicate prism
#
LinkedList::~LinkedList() {
    Node* currentNode = head_;
    Node* nextNode;
    while (currentNode != nullptr) {
        nextNode = currentNode->getNextNode();
        delete currentNode;
        currentNode = nextNode;
    }
    head_ = nullptr;
    tail_ = nullptr;
}
#
Node::~Node() {
    delete this;
}
#
class Node {
    public:
        Node(std::string &name, double value);
        ~Node();
        // Getters
        Node* getNextNode();
        std::string getName();
        double getValue();
        // Setters
        void setNextNode(Node* nextNode);
        void setName(std::string &name);
        void setValue(double value);
    private:
        Node* nextNode_;
        std::string name_;
        double value_;
    };
formal nebula
#

think about what it does

#

in your case, I think just writing ~Node() = default; in the header is enough

delicate prism
#

I googled that delete calls the destructor and assumed everything needed its own destructor, but I don't know what I should write in there

#

Do you mind explaining why it's bad?

#

I'm very new to memory allocations

formal nebula
delicate prism
#

Oh

#

then what does ```cpp
delete this;

formal nebula
# delicate prism Do you mind explaining why it's bad?

because you're calling delete this in its own destructor... but delete calls the destructor... but then the destructor does delete this which then calls the destructor... but then the destructor does delete this which calls the destructor...

delicate prism
#

would get a stackoverflow?

formal nebula
#

probably

delicate prism
#

I'll go on to delete the destructor then

snow lagoonBOT
#

@delicate prism Has your question been resolved? If so, run !solved :)

delicate prism
#

!solved

snow lagoonBOT
#

Thank you and let us know if you have any more questions!