Quick A: When you might delete polymorphically.
Recently on SO:
When to use virtual destructors?
Virtual destructors are useful when you might potentially delete an instance of a derived class through a pointer to base class:
class Base { // some virtual methods }; class Derived : public Base { ~Derived() { // Do some important cleanup } };Here, you'll notice that I didn't declare Base's destructor to be virtual. Now, let's have a look at the following snippet:
Base *b = new Derived(); // use b delete b; // Here's the problem!Since Base's destructor is not virtual and b is a Base* pointing to a Derived object, delete b has undefined behaviour...
Add a Comment
Comments are closed.