0

I have a List class that has nodes of type Node.

class List{
        Node* head;
        int size;
    
    public:
        List();
        List(const Team&, Node* = NULL);
        List& operator=(const List&);
        ~List();
        
        int getSize() const;
        void setSize(int);
        Node* getHead() const;
        void setHead(Node*);
};


class Node{
        Team value;
        Node* next;
    
    public:
        Node(const Team& = Team(), Node* = NULL);

        Team getValue() const;
        void setValue(const Team&);
        Node* getNext() const;
        void setNext(Node*);
};

The destructor for my List class works fine and empties the list. Should I also have a destructor for my Node class?

List::~List(){
while(head != NULL){
    Node *temp = head->getNext();
    delete head;
    head = temp;
    size--;
}

}

  • What unmanaged resources does the Node have ownership of that need to be handled in the destructor? – Eljay Dec 04 '20 at 18:02
  • maybe the duplicate looks unrelated becaue the quesiton doesn't mention the desctructor, but in fact if you ask yourself if you need a descructor you need to ask for the other special members too, so it basically is the same quesiton and the answers cover desctructors too of course – 463035818_is_not_an_ai Dec 04 '20 at 18:09
  • I keep nodes as dumb as possible. They should have enough brains to store the data and links to surrounding nodes. No setters, no getters, no constructors. Everything has `public` access, but the node itself is `private` within the linked list class, so only the linked list can mess with them. The linked list creates them via [aggregate initialization](https://en.cppreference.com/w/cpp/language/aggregate_initialization#Designated_initializers) and the linked list deletes them when it's done with them. If the nodes start making decisions, they have to make them in lockstep with the linked list – user4581301 Dec 04 '20 at 18:30
  • My node would look like: `struct Node{ Team value; Node* next; };` that's it. Simple and damn near foolproof. It observes the [Rule of Zero](https://en.cppreference.com/w/cpp/language/rule_of_three) because it has absolutely no responsibilities other than storing values that are managed by the Linked list. – user4581301 Dec 04 '20 at 18:32
  • No, is the simple answer. If you are not sure then ask yourself what you would actually do in that destructor. – john Dec 04 '20 at 19:16
  • I got it now, thank you everybody! – Stefan Nastase Dec 04 '20 at 20:08

0 Answers0