slaw
slaw

Reputation: 6869

Inherit Parent Constructor

I am new to Perl inheritance and haven't been able to find explicit instructions for inheriting the parent constructor. I assumed that all methods (including the constructor) from the parent class are inherited but it appears that this isn't the case. So, this is not enough:

package Child;
use strict;
use Parent;
our @ISA=qw(Parent);

Instead, I need to add a constructor that calls the parent constructor:

package Child;
use strict;
use Parent;
our @ISA=qw(Parent);

sub new {
  my $self=Parent::new(shift);
  bless $self;
  return $self;
}

Perhaps somebody can clarify the logic for me and tell me if the parent constructor be inherited without doing what I did above (explicit declaration and calling the parent constructor)?

Upvotes: 1

Views: 456

Answers (3)

Axeman
Axeman

Reputation: 29854

Often, if you want a constructor for one class to call the parent class, this will be handled by the "psuedo-class" SUPER.

package Derived;
use parent 'Base';

sub new { 
    my $class_name = shift;
    my $self       = $class_name->SUPER::new( @_ );

    return init_Derived( $self );
}

This will only work with single descent. With multiple parents, you have to bash it together yourself.

Upvotes: -1

tobyink
tobyink

Reputation: 13664

As per @ysth's answer, you shouldn't need to override the parent constructor unless you need to do something special in your constructor. In which case, the way you'd usually do it would be like this:

sub new {
   my $class = shift;
   my $self  = $class->SUPER::new(@_);
   ...;
   return $self;
}

At a guess, the reason inheritance is not working properly is that you might be using the one argument form of bless in the superclass. Something like this:

bless $self;

Except in very unusual circumstances, you should always prefer the two-argument version of bless:

bless $self, $class;

Where $class is the first argument passed to the new sub.

Upvotes: 0

ysth
ysth

Reputation: 98388

You do not need to do that; something is wrong somewhere else in your code.

This is a full working example:

main.pl:

use strict;
use warnings;
use Subclass;
my $object = Subclass->new();
print "object is a ", ref $object, "\n";

Subclass.pm:

package Subclass;
use strict;
use warnings;
use parent 'Superclass';
1;

Superclass.pm:

package Superclass;
use strict;
use warnings;
sub new {
    my $class = $_[0];
    return bless {}, $class;
}
1;

use parent 'Superclass' just loads Superclass and sets @ISA for you.

Upvotes: 6

Related Questions