C++ destructor for class object within another class

  c++

I am trying to implementing a SegmentTree class to be used in another Solution class.

In class SegmentTree, the destructor is implemented as follows:

~SegmentTree() {
    destruct(root);
};

void destruct(Node* root) {
    if (!root) return;
    
    destruct(root->left);
    destruct(root->right);
    delete root;
    root = NULL;
}

Then, in class Solution, we have

class Solution {
private:
    SegmentTree* tree;

public:
    Solution(vector<int>& nums) {
        tree = new SegmentTree(nums);
    }

    //Question: how shall ~Solution() be implemented to free memory of the pointer tree?
};

The question:

  1. Do we need to implement destructor to delete tree pointer in Solution class?
  2. If yes, how shall that be implemented?

Source: Windows Questions C++

LEAVE A COMMENT