Calling parent constructor

Discussion in 'Perl Misc' started by ed, Oct 9, 2003.

  1. ed

    ed Guest

    Is there anything wrong with calling the parent's constructor
    this way?

    It all seems to work as expected. For instance if I take the
    "printVars()" sub out of test3 the one in test2 executes.


    # -- start perl code

    { package test1;

    sub new
    {
    my $proto = shift;
    my $class = ref($proto) || $proto;
    my $this = {};
    bless($this, $class);

    print "in test1::new \n";

    $this->{test1} = 'this is test1';

    return $this;
    }
    }

    { package test2;

    use base qw(test1);

    sub new
    {
    $this = test1::new(@_);

    print "in test2::new \n";

    $this->{test2} = 'this is test2';

    return $this;
    }

    sub printVars
    { my $this = shift;

    print "in test2::printVars \n";
    }
    }

    { package test3;

    use base qw(test2);

    sub new
    {
    $this = test2::new(@_);

    print "in test3::new\n";

    $this->{test3} = 'this is test3';

    return $this;
    }

    sub printVars
    { my $this = shift;

    print "\$this->{test1} = $this->{test1} \n";
    print "\$this->{test2} = $this->{test2} \n";
    print "\$this->{test3} = $this->{test3} \n";
    }
    }

    $obj = test3->new();
    $obj->printVars();

    #-- end perl code

    tia,
    --ed
    ed, Oct 9, 2003
    #1
    1. Advertising

  2. ed

    ed Guest

    I believe I found out that this is the right way to do it:

    $this = $this->SUPER::new(@_);

    You just have to make sure you've placed the parent classes into the
    @ISA array in the right order.

    --ed
    ed, Oct 9, 2003
    #2
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Duncan Aitken
    Replies:
    1
    Views:
    678
    Jack Klein
    Sep 20, 2004
  2. pantalaimon
    Replies:
    3
    Views:
    51,034
    John Harrison
    Oct 9, 2004
  3. Christian Dieterich

    inherit without calling parent class constructor?

    Christian Dieterich, Jan 26, 2005, in forum: Python
    Replies:
    3
    Views:
    395
    Jeff Shannon
    Jan 26, 2005
  4. Replies:
    6
    Views:
    495
  5. Generic Usenet Account
    Replies:
    10
    Views:
    2,202
Loading...

Share This Page