Impossible overload constructor in perl

New to OOP perl ... The first program, not a bale to overload the constructor. I tried a lot of things, maybe I'm still missing a few things!

Base class:

#!/usr/bin/perl
use strict;
package Person;
sub new
{
my($class)=shift;
my($self)={ 
        _name=>shift,
        _sname=>shift,
};
bless $self, $class;
return $self;
}       
1;  

Derived class:

#!/usr/bin/perl
package Employee;
use strict;
use Person;
our @ISA = qw(Person);
sub new
{
my($class)=@_;
my($self)=$class->SUPER::new($_[1],$_[2]);
my $self1={
        _id=>$_[3],
        _sal=>$_[4],
};
bless $self1,$class;
return ($self);
}
1;

The main program:

#!/usr/bin/perl
use strict;
use Data::Dumper;
use Employee;

sub main
{
my($obj)=Employee->new("abc","def","515","10");
print Dumper $obj;
}
main();

I cannot get the values ​​of the members of a base class class. Do not get what I missed in the program. Help me.

+3
source share
1 answer

There is no need for an object named $self1in your derived constructor. You should just say:

sub new {
    my($class)=@_;
    my($self)=$class->SUPER::new($_[1],$_[2]);
    $self->{_id} = $_[3];
    $self->{_sal} = $_[4];
    # no need to bless -- $self is already blessed correctly in SUPER::new
    return ($self);
}
+7

All Articles