10.2. Beating a Dead HorseBecause the destructor method is inherited, you can also override and extend superclass methods. For example, we'll decide the dead horses need a further use: ## in Horse sub DESTROY { my $self = shift; $self->SUPER::DESTROY; 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 your destructors (even if you don't yet have any base/parent classes). Whether you call it at the beginning or the end of your own destructor is a matter of hotly contested debate. If your derived class needs some superclass instance variables, you should probably call the superclass destructor after you complete your 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. There's no rule of thumb, even. Sorry. Copyright © 2003 O'Reilly & Associates. All rights reserved. |
|