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
In reply to maintaining constructor inheritance cascade by jaa
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |