[Cs3] virtual destructors

Mikhail Nesterenko mikhail at cs.kent.edu
Tue Feb 11 17:08:02 EST 2014


> The other question I had involves destructors; I've seen:
>
> virtual ~Test();
> 
> used many times for base classes, but after testing how destructor
> inheritance works, I couldn't find a difference between virtual and
> non-virtual destructors?

The reasons base-class destructors are usually declared virtual is as
follows. Consider the Abstract Factory Template Method we have just
studied and the "Making Pizza" example here:

  http://www.cs.kent.edu/~mikhail/classes/cs3/Examples/AbstractFactory/abstractFactoryPizzas.cpp	

Let the client code be as follows:

    PizzaFactory bestPizzaShop; // declaring concrete factory
    
    // using a concrete factory to create (allocate) one concrete
    // product and returning its address
    // the address is assigned to pointer of abstract class (bread)
    Bread *myBread = bestPizzaShop.makeBread(9.99, "Pizza", "pepperoni");

    // manipulating product here


    // deallocating product
    delete myBread;

Now, the question is which destructor is to be invoked at
deallocation? If destructor is virtual, then even though the pointer
"myBread" is of base class, through run-time binding, the destructor
of the derived class (concrete product) would be invoked. This
destructor would properly deallocate the object of the derived class
(pizza).

If, however, the destructor is not virtual, then the destructor of the
base class is to be invoked. According to C++ standard, the result of
the invocation of the destructor of the base class on the derived
class object is unspecified. In reality, it would probably result in
incomplete deallocation of the object (only base class is deallocated)
and a subtle memory leak.

So a good practice is to make destructors of base classes virtual.

Thanks,
-- 
Mikhail


More information about the cs3 mailing list