Maria Ines Parnisari
Maria Ines Parnisari

Reputation: 17496

Calling abstract classes' destructors

I've got three classes.

class Son : public Father;

class Father : public Grandfather;

Father is abstract and so is Grandfather. Son is NOT abstract.

If I do this:

Son* son = new Son();

and then do this:

delete(son)

how do I make sure that the destructors of Father and Grandfather are called?

Upvotes: 2

Views: 839

Answers (1)

Collin
Collin

Reputation: 12287

Destructors of parent classes to your pointer will be called no matter what.

You should make the top level class's destructor virtual though, so you can delete a pointer to a Grandfather and ensure all the subclass's destructors are called as well. Not doing so leads to undefined behavior, which is always a bad thing.

Once a function is virtual, it will be virtual for the entire derivation tree, no need to mark it in child classes. However, it's usually good form to do so, it helps people reading the code.

Upvotes: 3

Related Questions