I have a recursive problem I'm trying to solve. If a given action is possible, there may exist additional child actions, and so forth. My solution is a class like this:
// MyObj.h
#include <vector>
class MyObj
{
private:
std::vector<MyObj*> _children;
public:
void addChild(MyObj* m);
}
// MyObj.cpp
#include "MyObj.h"
void MyObj::addChild(MyObj* m)
{
MyObj::_children.push_back(m);
}
I'm using the class like this:
MyObj m;
MyObj *child = new MyObj();
m.addChild(child);
My understanding is that since I allocated child
on the heap, I need to destroy it later. If the code that creates that object doesn't maintain that reference, it's going to be up to the parent object to destroy it. Is it appropriate to define a destructor like this:
MyObj::~MyObj()
{
for (std::size_t i = 0; i < MyObj::_children.size(); i++)
{
delete MyObj::_children[i];
}
}
Am I on the right track with this, or is my approach flawed?
PS: I apologize if this is a direct duplicate, as I know there are lots of questions already dealing with destructors; I read a bunch but still didn't feel confident. I am pretty inexperienced with C++ and figured a direct question would be most helpful to me.