Home > front end >  How should I define my destructor for the Node class in C ?
How should I define my destructor for the Node class in C ?

Time:11-26

I am supposed to implement a class of Nodes for the tree that consists of static nodes (for educational purposes). The classes headers look like this:

class CNodeStatic
{
private:
    int i_val;
    CNodeStatic *pc_parent_node;
    vector<CNodeStatic> v_children;
public:
    CNodeStatic() {i_val =0; pc_parent_node = NULL;};
    ~CNodeStatic();
    void vSetValue(int iNewVal) {i_val = iNewVal;};
    int iGetChildrenNumber() {return (v_children.size());};
    void vAddNewChild();
    void vAddChild(CNodeStatic pcChildNode);
    CNodeStatic *pcGetChild (int iChildOffset);
};
class CTreeStatic
{
private:
    CNodeStatic c_root;
public:
    CTreeStatic();
    ~CTreeStatic();
    CNodeStatic *pcGetRoot() {return (&c_root);};
    bool bMoveSubtree(CNodeStatic *pcParentNode, CNodeStatic *pcNewChildNode);
    void vPrintTree();
};

However I am not sure how the destructor for such class should look like. I know that we need to define destructors when there is a dynamically allocated memory or pointer in class. In this case it's pc_parent_node that points to the parent of the node. However if I try to define my destructor only as delete pc_parent_node the program won't work.

CodePudding user response:

I know that we need to define destructors when there is a dynamically allocated memory or pointer in class

Right. If a class manages a resource, it must manage the resource and cleaning up is part of that.

In this case it's pc_parent_node that points to the parent of the node.

Pointers != managing a resource. In particular, raw pointers should not be used to manage lifetime.

The shown code does not dynamically allocate something. The class does not seem to own a resource, hence there is nothing it must delete in its destructor. If it does manage a resource, it should do so by using a smart pointer or container.

Read about the rule of zero (https://en.cppreference.com/w/cpp/language/rule_of_three). A class that manages a resource should do only that and nothing else. In all other cases you should strive to follow the rule of zero by delegating lifetime managment to smart pointers or containers. The best destructor is a destructor that the compiler can generate. Only if that is not sufficient you need to manually manage something.

  • Related