Accessing Overridden Methods

Problem

Your constructor method overrides the constructor of a parent class. You want your constructor to call the parent class’s constructor.

Solution

Learn about the special class, SUPER.

sub meth { 
    my $self = shift;
    $self->SUPER::meth();
}

Discussion

In languages like C++ where constructors don’t actually allocate memory but just initialize the object, all base class constructors are automatically called for you. In languages like Java and Perl, you have to call them yourself.

To call a method in a particular class, the notation $self->SUPER::meth() is used. This is an extension of the regular notation to start looking in a particular base class. It is only valid from within an overridden method. Here’s a comparison of styles:

$self->meth();                # Call wherever first meth is found
$self->Where::meth();         # Start looking in package "Where"
$self->SUPER::meth();        # Call overridden version

Simple users of the class should probably limit themselves to the first one. The second is possible, but not suggested. The last must only be called from within the overridden method.

An overriding constructor should call its SUPER’s constructor to allocate and bless the object, limiting itself to instantiating any data fields needed. It makes sense here to separate the object allocation code from the object initialization code. We’ll name it with a leading underscore, a convention indicating a nominally private method. Think of it as a “Do Not Disturb” sign.

sub new { my $classname ...

Get Perl Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.