2

As I know in cpp, when we delete an object or when the main finishes, the destructors of all objects will be called. For those objects whose type are class child, the destructors of class child will be called first then the distructors of class parent will be called.
Now I am confused. Because if a pure virtual destructor is allowed, how could it be called when we delete an object of class child? Doesn't it call the destructor of class parent which is pure virtual?

Yves
  • 11,597
  • 17
  • 83
  • 180
  • The pure virtual destructor declaration in the base class forces any derived classes to implement the destructor so if you have a pointer to the base class and delete it then the derived classes dtor is then called – EdChum May 27 '15 at 08:13

1 Answers1

4

Yes, the destructor of the base class is called. This means it must have an implementation. It is possible to provide an implementation for any pure virtual function, including the destructor. For example:

struct foo
{
    virtual ~foo() = 0; // pure virtual dtor
};

foo::~foo() {} // implementation

The use-case of a pure virtual destructor is to ensure a class without any other pure virtual methods cannot be instantiated.

juanchopanza
  • 223,364
  • 34
  • 402
  • 480