in reply to Re^2: Why is the base class's destructor not called?
in thread Why is the base class's destructor not called?
Objects (class instances) are represented by blessed references.
When blessed reference goes out of scope (or otherwise becomes eligible for destruction), the cleanup code (only) calls a DESTROY method within the class that that reference is blessed into.
Since your instance is of class B; only B's destructor is called automatically. It is up to the writer of class B to call any base-class or delegate destructors that need to be called from B's DESTROY method.
As for the 'apparent order' or destructor calls, it all depends upon how you choose to trace them. If you output your trace messages on entrance to the destructors:
package A; ... sub DESTROY { warn 'A::DESTROY' ... return; } package B; ... sub DESTROY { warn 'B::DESTROY'; my $self = shift; $self->SUPER::DESTROY; return; }
Then class Bs destructor appears to be called before class A's. But do it this way:
package A; ... sub DESTROY { ... warn 'A::DESTROY' return; } package B; ... sub DESTROY { my $self = shift; $self->SUPER::DESTROY; warn 'B::DESTROY'; return; }
And it will appear to happen the other way around. So, appearances aren't everything.
The main difference between Perl and C++ in this regard is that in Perl, the destructors are called recursively, and the programmer gets to decide which order things happen in (or if at all).
In C++; destructors are called iteratively in a fixed (youngest to oldest) order.
|
|---|