shemp has asked for the wisdom of the Perl Monks concerning the following question:

Heres an annoying little problem with polymorphism. I have 2 classes, call them parent & child, and the constructors take an initialization param whose accessor / mutator is overridden, but the parent initializer always gets called, because in the parent constructor, the object instance is still a parent, not a child.
package parent; sub new { my $class = shift; my ($setup_data) = @_; my $self = {}; bless $self, $class; $self->_SetupData($setup_data); return $self; } package child; use base qw(parent); sub new { my $class = shift; my ($setup_data) = @_; my $self = $class->SUPER::new($setup_data); return $self; }
So i understand why child::_SetupData() isnt called from parent::new(), but im looking for a clean way to fix this problem, without taking the initialization out of the constructors, and into a setup method that must be explicitly called.

Replies are listed 'Best First'.
Re: class implementation question
by dws (Chancellor) on Jul 15, 2004 at 21:36 UTC

    ... because in the parent constructor, the object instance is still a parent, not a child.

    Are you sure? Try adding

    print "The instance is a ", ref($self), "\n";
    right after you bless.

Re: class implementation question
by mojotoad (Monsignor) on Jul 15, 2004 at 21:30 UTC
    Sounds to me like what you're really hoping for is inheritable class data. If that's true, then you will no doubt be interested in Class::Data::Inheritable.

    Otherwise you'll probably need a factory class/method that calls the configuration method separately after the constructor.

    Matt

Re: class implementation question
by shemp (Deacon) on Jul 15, 2004 at 22:07 UTC
    Ok, im brain dead, i have no idea what was going on. Things are working as they should, that you both for your answers. I must have not saved a final version of one of the files when i was testing...editing in too many terms at once.