in reply to To bless or not to bless

The Employee constructor is:
sub new { my $class = shift; my $self = $class->SUPER::new(); $self->{SALARY} = undef; $self->{ID} = undef; $self->{START_DATE} = undef; bless ($self, $class); # reconsecrate return $self; }
When you do
my $emp = Employee->new;
the $self returned by
my $self = $class->SUPER::new();
will be blessed into the Person package, so to be able to call the methods that Employee has beyond those in Person, $self needs to be reblessed into the class that Employee::new was invoked on (i.e. Employee or a subclass of it).

Update

The answer above would apply if the first version of Person::new() in perltoot (i.e. the one that doesn't bless $self into $class) were being used. As ikegami points out, the rebless isn't needed if Person::new() does bless $self into $class.

Replies are listed 'Best First'.
Re^2: To bless or not to bless
by ikegami (Patriarch) on Nov 30, 2009 at 18:25 UTC

    the $self returned by my $self = $class->SUPER::new(); will be blessed into the Person package,

    No it won't unless there's a bug in the parent class. $class contains "Employee", not "Person". The reblessing is unneeded.

      I've checked .....

      Given the following code

      I get the result

      Don Federico Jesus Pichon Alvarez is age 47. His peers are: PEON=FRANK, PEON=FELIPE, PEON=FAUST here is the boss $VAR1 = bless( { 'ID' => undef, 'PEERS' => [ 'Frank', 'Felipe', 'Faust' ], 'NAME' => undef, 'AGE' => 47, 'SALARY' => 40000, '_CENSUS' => \1, 'FULLNAME' => bless( { 'SURNAME' => 'Pichon Alvarez', 'TITLE' => 'Don', 'CHRISTIAN' => 'Federico Jesus +', 'NICK' => 'Fred' }, 'Fullname' ) }, 'Boss1' ); Destroying $self Fred at ./testboss1.pl line 0 All persons are going away now

      Boss1 inherits Employee4 which in turn inherits Person5. Neither Boss1 nor Employee4 bless. When a new Boss1 is instantiated the Employee4 constructor is called which in turn calls the Person5 constructor. The value of $class in both Person5 and Employee4 is Boss1. So Person5 artifacts (methods, globals and data) are blessed into the Boss1 class as are Employee4 artifacts.

      This would indicate that reblessing isn't entirely necessary, even when subclassing.

      But it might be reckless to assume that blessing occurs somewhere in the hierarchy.

        But it might be reckless to assume that blessing occurs somewhere in the hierarchy.

        Not at all. You are purposefully calling new to create and return an object. Expecting it to return an object is not reckless.

Re^2: To bless or not to bless
by LesleyB (Friar) on Nov 30, 2009 at 17:38 UTC

    Thank you