C++ deleting children basing on parent's pointer

Viewed 610

Let's say that I have class A:

class A {
    A();
};

and class B being a child of A:

class B : public A {
    B() : A();
    ~B();
};

and a vector of A pointers:

std::vector<A*> a_pointers;

Now, I initialize everything with:

B* b_obj = new B();

a_pointers.push_back(b_obj);

How do I delete b_obj object? Should it be something like this?

delete a_pointers[0];

Would it work? If not, how should it be done?

2 Answers

You'll want to give A a virtual destructor (see here for why):

class A {
    A();
public:
    virtual ~A() = default; 
};

At which point calling delete a_pointers[0] will fully destruct b_obj.

If you specifically refer to the local variable B* b_obj then you don't need to delete it. The local variable resides in the stack and will be cleaned when you return from the function it was declared in.

If you are referring to the object that was created and assigned to B* b_obj (i.e. the object that was created by new() and then it's reference was copied into the vector), then you would need to delete it explicitly by calling delete() sometime later on (you would probably need to iterate through the vector and delete all of its items).

Another important thing to notice is that you would also need to declare your destructor as virtual as Nathan Pierson said.

Related