Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inheritance and default constructor in perl

I have the following code :-

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

like image 901
AAB Avatar asked Jan 18 '26 14:01

AAB


1 Answers

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.

like image 162
Chris Jester-Young Avatar answered Jan 21 '26 05:01

Chris Jester-Young



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!