Mandar Pande
Mandar Pande

Reputation: 12974

Not able overload constructor in perl

New to OOP perl...First program, not bale to overload constructor. I have tried many things, may be I'm still missing 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;

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'm not able to get values of base class class members. Not getting what i miss in the program. Help me out.

Upvotes: 3

Views: 647

Answers (1)

mob
mob

Reputation: 118605

There's no need for an object called $self1 in 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);
}

Upvotes: 7

Related Questions