Virtual Destructors
Object-oriented languages typically manage memory allocation and deallocation automatically when objects are created and destroyed. However, some object-oriented languages allow a custom destructor method to be implemented, if desired. If the language in question uses automatic memory management, the custom destructor (generally called a finalizer in this context) that is called is certain to be the appropriate one for the object in question. For example, if an object of type Wolf that inherits Animal is created, and both have custom destructors, the one called will be the one declared in Wolf.
In manual memory management contexts, the situation can be more complex, particularly as relates to static dispatch. If an object of type Wolf is created but pointed to by an Animal pointer, and it is this Animal pointer type that is deleted, the destructor called may actually be the one defined for Animal and not the one for Wolf, unless the destructor is virtual. This is particularly the case with C++, where the behavior is a common source of programming errors.
While it might seem as though non-virtual destructor behavior is never the right thing, in very memory- or CPU-constricted environments where the overhead of polymorphism is not desired, and where objects are never deleted polymorphically, avoiding the construction of a virtual function table may be considered a worthwhile optimization.
Read more about this topic: Virtual Function
Famous quotes containing the word virtual:
“Tragedy dramatizes human life as potentiality and fulfillment. Its virtual future, or Destiny, is therefore quite different from that created in comedy. Comic Destiny is Fortunewhat the world will bring, and the man will take or miss, encounter or escape; tragic Destiny is what the man brings, and the world will demand of him. That is his Fate.”
—Susanne K. Langer (18951985)