Search code examples
c++objectpointersparentchildren

C++ deleting children basing on parent's pointer


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?


Solution

  • 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.