jaa has asked for the wisdom of the Perl Monks concerning the following question:
I have looked in object oriented section Q&A for something like this, but didn't quite find the slant I am looking for.
When I create a child class, how should I ensure that the parent class constructor is properly called?
I am currently doing something like this - is there a better way?
use strict; # This should do ALL the _initXXX()s # even though myGrandChild does not know # about _initParent() or _initChild()! my $it = myGrandChild->new('a','b','c'); #---------------------------------- package myParent; our @ISA; sub new { my $class = shift; my $self = $ISA[0] ? $ISA[0]->new(@_) : {}; bless $self,$class; $self->_initParent(@_); return $self; } sub _initParent { my $self = shift; print "_initParent @_ [ISA: @ISA]\n"; } #---------------------------------- package myChild; our @ISA; use base qw(myParent); sub new { my $class = shift; my $self = $ISA[0] ? $ISA[0]->new(@_) : {}; bless $self,$class; $self->_initChild(@_); return $self; } sub _initChild { my $self = shift; print "_initChild @_ [ISA: @ISA]\n"; } #---------------------------------- package myGrandChild; our @ISA; use base qw(myChild); sub new { my $class = shift; my $self = $ISA[0] ? $ISA[0]->new(@_) : {}; bless $self,$class; $self->_initGrandChild(@_); return $self; } sub _initGrandChild { my $self = shift; print "_initGrandChild @_ [ISA: @ISA]\n"; } #----------------------------------
Obviously calling _initXXX()s is a facet of this being a trivial example - a number of classes in our library do more complex things when created. Also, they are not all in-house, so enforcing an additional naming standard - i.e. assuming that there is a $self->SUPER::_init() does not work.
Regards,
Jeff
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: maintaining constructor inheritance cascade
by dragonchild (Archbishop) on May 14, 2003 at 14:12 UTC | |
by jaa (Friar) on May 14, 2003 at 14:35 UTC | |
by dragonchild (Archbishop) on May 14, 2003 at 15:09 UTC | |
by tilly (Archbishop) on May 14, 2003 at 15:30 UTC | |
by jaa (Friar) on May 14, 2003 at 15:31 UTC | |
by chip (Curate) on May 14, 2003 at 16:08 UTC | |
|
Re: maintaining constructor inheritance cascade
by jaa (Friar) on May 14, 2003 at 13:37 UTC | |
|
Re: maintaining constructor inheritance cascade
by Anonymous Monk on May 14, 2003 at 15:31 UTC | |
by jaa (Friar) on May 14, 2003 at 16:43 UTC |