ajwood ajwood - 5 months ago 8
Perl Question

Can I make a Perl subclass without implementing a child constructor?

Is it possible in Perl to make a subclass without implementing a constructor? I don't need any subclass-specific constructor behaviour, so I'd like to inherit from the parent.

In this example, I have a base class

Base.pm
and a child class
Child.pm
. The
Child
class should simply override one of its parent's methods:

enter image description here

When I run test.pl, the Base class's exec method gets executed (I assume it's because the object gets blessed as
Base
in the
Base.pm
constructor).

$ ./bin/test.pl
I'm the Base class


Is there a way to implement a child class without having to reimplement a constructor?

Answer

Yes.

You effectively have the following:

sub new {
   return bless({});
}

Replace it with the following:

sub new {
   my $class = shift;
   return bless({}, $class);
}

Basically, always use bless's two-argument form.


How I write my constructors:

  • Base classes:

    sub new {
       my ($class, ...) = @_;
       my $self = bless({}, $class);
       $self->{...} = ...;
       return $self;
    }
    
  • Derived classes:

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