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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With