I am working on an implementation of a binary tree in C++. I am fairly new to the language, and while I understand what structs and destructors are, I am not sure about what happens with nested classes/structs.
In my implementation, I have a nested struct for my binary node. Does this struct need its own destructor, or will all of the nodes be deleted when the destructor for the binary tree itself get called. Does the answer change if I change the struct to a class?
Also, I was told that if you ever call “new” in a class, you need to call “delete” in the destructor. If I initialize an array in my initialization list for a class (i.e. class: array({0})), do I need to delete [] array in my destructor?
Nesting one class (or struct) within another has no effect on the lifetime of the objects. All it does is provide a scope for the class’s name, and access to private members in the enclosing class. So your tree nodes won’t be automatically destroyed just by virtue of being nested in the tree class.
If you want a tree’s nodes to be destroyed when the tree itself is destroyed, you need to ensure that the tree’s destructor does that. If you’re allocating the nodes manually with
new, usedelete(ordelete[]) in the destructor. Alternatively, you can use something likestd::auto_ptr(orstd::unique_ptrin C++11), which will do the cleanup in its own destructor so you don’t have to write thedeletecalls yourself.Changing a struct to a class has no effect on its behavior at runtime. The only difference between a struct and a class in C++ is that a struct’s body implicitly begins with
public:and a class’s body implicitly begins withprivate:.