In C++, you would have to declare X::foo() to be virtual:package X; sub foo; sub bar; package Y; @ISA = 'X'; sub foo; package main; X->foo; # calls X::foo('X'); X->bar; # calls X::bar('X'); Y->foo; # calls Y::foo('Y'); Y->bar; # calls X::bar('Y');
You don't need to do that in Perl, since an object's method search tree starts in the object's class (Y, in this case).// yes, this is C++, so shoot me class X { public: virtual int foo () { return 1; } int bar () { return 2; } }; class Y : public X { virtual int foo () { return 3; } };
and it will accept an object of class Y (because of the rules of inheritance). In Perl, you can do this checking via the isa() method shown above.void printStuff (X& obj);
And then a program would run like:package Employee; sub new { my ($class,$fname,$lname) = @_; die if $class eq 'Employee'; bless { FNAME => $fname, LNAME => $lname }, $class; } package Employee::Boss; @ISA = qw( Employee ); sub new { my ($class,$fname,$lname) = @_; my $self = $class->SUPER::new($fname,$lname); $self->{PAY} = 1_000_000; bless $self, $class; } # and so on...
use Employee; # defines Employee, Employee::Boss, # Employee::Hourly, and Employee::Intern $joe = Employee::Intern->new('Joe', 'Schmoe'); $jay = Employee::Boss->new('Jay','Schmay'); $not = Employee->new('Not', 'Happening'); # <-- dies
In reply to RE: Re: Best Method of Object-Oriented Behavior Addition?
by japhy
in thread Best Method of Object-Oriented Behavior Addition?
by princepawn
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |