O'Reilly logo

Perl Cookbook by Nathan Torkington, Tom Christiansen

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required