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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.