I’m writing a class that holds a pointer to a parent object of the same type (think Qt’s QObject system). Each object has one parent, and the parent should not be destroyed when a child is destroyed (obviously).
class MyClass
{
public:
MyClass(const MyClass* ptr_parent): parent(parent){};
~MyClass(){ delete[] a_children; };
private:
const MyClass* ptr_parent; // go to MyClass above
MyClass* a_children; // go to MyClass below
size_t sz_numChildren; // for iterating over a_children
}
(Excuse my inline coding, it’s only for brevity)
Will destroying the “Master MyClass” take care of all children? No child should be able to kill it’s parent, because I would then have pointers in my main program to destroyed objects, correct?
Why might you ask? I need a way to “iterate” through all subdirectories and find all files on a platform independent level. The creation of this tree will be handled by native API’s, the rest won’t. Is this a good idea to start with?
Thanks!
This concept is fine, but there are a number of things wrong with the code you posted (although I gather from your comment about “inline coding” that you just wrote this on the fly rather than copying it out of a compilable program).
You will need to have
a_childrenbe an array ofMyClasspointers, so it will need to have typeMyClass**, and you will need to allocate it an reallocate it appropriately as children are added.delete[] a_childrenwill not delete the children, it will delete the array that holds the pointers to the children. You must, in theMyClassdestructor, iterate over the array, deleting each child pointer, and then delete the array. In fact, it would probably be a better idea to use astd::vector<MyClass*>fora_childreninstead ofMyClass*, so then you don’t have to worry about (1). But even with a vector, you will still need to iterate and delete each child in the destructor.Your children will need to “register” with their parent object somehow. The way you have written this, there is no way for the child object to tell the parent object that it exists. For this reason you probably will not be able to get away with passing a const parent pointer.
So, as an example:
Note that this does not take into account the possibility that children will be destroyed by any means other than destroying their parent.