Object-Oriented Programming

Virtual Destructors

Michael L. Collard, Ph.D.

Department of Computer Science, The University of Akron

virtual

  • Methods can be virtual or non-virtual
  • Constructors cannot be virtual
  • What about destructors?

Classes

Usage

Run

Problem

  • When using a Base pointer with a Derived object, the Derived destructor is not called
  • Not only is the Derived destructor not called, the destructor for any fields/data members is also not called
  • Why?
    • Compiler uses static dispatch to setup call to destructor
  • Solution:
    • virtual Destructor

Virtual Destructor Classes

Virtual Destructor Usage

Virtual Destructor Run

Class Comparison

Run Comparison

Conclusion

  • Any base class with a virtual method should have a virtual destructor
  • If there is nothing to do in the destructor, use the default constructor specifier