Yes, you can override the class destructor. In fact, when you define a class hierarchy that uses polymorphism, you must declare a virtual destructor in the base class.
Overrides of destructors work just like overrides of normal member functions work in that when you destroy an object by deleting an object through a pointer to the base class, the destructor of the derived class is correctly called. This is why you must have a virtual destructor in the base class for polymorphic hierarchies.
However, there is a difference between virtual destructors and virtual member elements that have nothing to do with the nature of the virtual destructor. That is, when executing the code:
class A { public: virtual void Foo() {} virtual ~A() {}; }; class B : public A { public: void Foo() {}; ~B() {} }; int main() { A* a = new B; a->Foo();
... when you call a->Foo() , the Foo() method in B called. Since B::Foo() does not explicitly call A::Foo() , A::Foo() not called.
However, when an object is destroyed through delete a; , first the destructor B::~B() is called, and then after that it ends, but before the control returns to the program, the base class destructor A::~A() also called.
Of course, this is obvious when you think about it, and again it has nothing to do with the nature of the virtual destructor, but it behaves differently than the usual call to the virtual method, so I thought d specify this.
Mandatory standard quotation:
[C ++ 03] 12.4 / 6: Destructors
After executing the body of the destructor and destroying any automatic objects allocated inside the body, the destructor for class X calls destructors for direct elements of Xs, destructors for Xs direct base classes and, if X is the type of the derived class itself (12.6.2), its destructor calls destructors for virtual base Xs classes. All destructors are invoked as if they referred to a qualified name, that is, they ignored any possible virtual redefinition of destructors in more derived classes. Foundations and members are destroyed in the reverse order of completion of their constructor (see 12.6.2). The return statement (6.6.3) in the destructor cannot directly return to the caller; before transferring control to the caller, destructors for members and bases are called. Destructors for array elements are called in the reverse order of their construction (see 12.6).