开发者

Inheritance and default constructor in perl

I have the following code :-

packa开发者_StackOverflowge A;

sub new{
 //constructor for A
}

sub hello{
 print "Hello A";
}

1;

package B;
use base qw(A);

sub hello{
 print "Hello B";
}

1;

My question is how can I instantiate B i.e. my $b = B->new(), without giving a constructor to B, what changes do I need to do in A to achieve this. Is this possible ?

Thanks.


Yes. Use this as A's new method:

sub new {
    my ($cls, @args) = @_;
    # ...
    my $obj = ...;  # populate this
    bless $obj, $cls;
}

The key is that when using B->new, the first argument is B (which I bound to $cls in my example). So if you call bless using $cls, the object will be blessed with the correct package.


In line with Chris' answer, your code should now look like:

package A;
sub new{
    my ( $class ) = @_;
    my $self = {};
    bless $self, $class;
}
sub hello{
    print "Hello A";
}

package B;
use base qw(A);
sub hello{
    print "Hello B";
}

package main;
my $b = B->new;
$b->hello;

B simply inherits A's constructor.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜