Dan Anderson wrote:

> Is it possible to call the constructor that a function inherits from its
> parent?  I tried calling SUPER:: and SUPER-> in a constructor and got
> errors.  Am i correct in assuming that if I rewrite the constructor that
> a copy of the parent object won't be available?

If you have a copy of the derived object, you have a copy of the parent
object.  The relationship is an "izza", not a 'hazza'.  No containment is
going on in an OO inheritance relationship.  To answer your immediate
question, there is a way to call functions of the parent, but with another
step in indeirection:
$child_class->SUPER->new.

You should rarely need this though.  Any attributes [ie hash members] of the
parent class that are relevant in your child object can simply be addressed
thorugh the constructor of the child class.  Any instance methods are
automatically available.  If they have not been overshadowed by redfinition
in the derived package, they will be available just as defined in the root
class.

package MyParent;

use Exporter;

our @ISA = 'Exporter';
our @EXPORT = qw /all/;

sub new {
  my $class = shift;
  my $self = {};
  bless $self, $class;
  $self->{name} = $_[0];
  $self->{age} = $_[1];
  return $self;
}

sub bemoan_age {
  my $self = shift;
  print "Oh what a drag it is getting old.  I can't believe $self->{name}" .

  " has been around $self->{age} years\n";
}

package MyChild;

use MyParent;

our @ISA = ('MyParent');

sub new {
  my $class = shift;
  my $name = shift;
  my $age = shift;
  my $self = $class->SUPER::new($name, $age);
  return $self;
}

sub print_stats {
  my $self = shift;
  print "Name: $self->{name}\n";
  print "Age:  $self->{age}\n";
}

Greetings! E:\d_drive\perlStuff>perl -w -MMyChild
my $kid = MyChild->new('Joseph', [huh?]);
$kid->print_stats;                # derived class method
$kid->bemoan_age;            #  parent class method
^Z
Name: Joseph
Age:  [huh?]
Oh what a drag it is getting old.  I can't believe Joseph has been around
[huh?] years

Well, that worked, but note that the following constructor for the MyChild
object worked just as well:


sub new {
  my $class = shift;
  my $name = shift;
  my $age = shift;
  my $self = {};
  bless $self, $class;
  $self->{name} = $name;
  $self->{age} =  $age;
  return $self;
}

and the name and age attributes set through the child constructor were just
as available to the bemoan_age accessor provided by the base class.  I'm not
sure I see any benefit to calling SUPER:: methods except in cases where a
parent method is overshadowed but still needed.

Joseph


-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>


Reply via email to