You can't have virtual constructors, but a virtual destructor makes it possible to destroy an object through a base class pointer while calling the derived destructors apropriately.
For example, dont actually run this code
class A {
public:
A() {}
~A() {}
};
class B : public A {
public:
B() {}
virtual ~B() {}
};
class C : public B {
public:
C() : _p( new int(0) ) {}
~C() { delete _p; std::cout << "Deleted p" << std::endl; }
private:
int *_p;
};
int main() {
C *c1 = new C();
C *c2 = new C();
B *bPointer = c1;
A *aPointer = c2;
std::cout << "Deleting through B*" << std::endl;
delete bPointer; // "deleted p"
std::cout << "------------" << std::endl;
std::cout << "Deleting through A*" << std::endl;
delete aPointer; // No output
return 0;
}
Class A's destructor should've been marked as virtual. You only need to write virtual on the topmost class of the hierarchy.