Section 13.3.  Beating a Dead Horse

Table of Contents

13.3. Beating a Dead Horse

Because the destructor method is inherited, we can also override and extend superclass methods. For example, we'll decide the dead horses need a further use. In our Horse class, we override the DESTROY method we inherited from Animal so we can do extra processing. However, since the Animal class might be doing things we aren't supposed to know about, we call its version of DESTROY using the SUPER:: pseudo-class we saw in Chapter 11.

## in Horse
  my $self = shift;
  print "[", $self->name, " has gone off to the glue factory.]\n";

my @tv_horses = map Horse->named($_), ('Trigger', 'Mr. Ed');
$_->eat('an apple') for @tv_horses;     # their last meal
print "End of program.\n";

This prints:

Trigger eats an apple.
Mr. Ed eats an apple.
End of program.
[Mr. Ed has died.]
[Mr. Ed has gone off to the glue factory.]
[Trigger has died.]
[Trigger has gone off to the glue factory.]

We'll feed each horse a last meal; at the end of the program, each horse's destructor is called.

The first step of this destructor is to call the parent destructor. Why is this important? Without calling the parent destructor, the steps taken by superclasses of this class will not properly execute. That's not much if it's simply a debugging statement, as we've shown, but if it was the "delete the temporary file" cleanup method, you wouldn't have deleted that file!

So, the rule is:

Always include a call to $self->SUPER::DESTROY in our destructors (even if we don't yet have any base/parent classes).

Whether we call it at the beginning or the end of our own destructor is a matter of hotly contested debate. If our derived class needs some superclass instance variables, we should probably call the superclass destructor after we complete our operations, because the superclass destructor will likely alter them in annoying ways. On the other hand, in the example, we called the superclass destructor before the added behavior, because we wanted the superclass behavior first.

Table of Contents
© 2000- NIV