in reply to Overriding methods and Inheritance

This ended up calling back to my overridden funcB() method as the hash passed in is blessed into my class.

Yes. Yes it does. That's the way polymorphism works and is nothing specific to Perl.

package Dog; sub pull_tail { $self->speak; } sub speak { print "Woof!\n"; } package AngryDog; sub speak { print "Grrrrr...\n"; }
What would you expect to happen when you pull an AngryDog's tail? That it would bark (because pull_tail is defined by the base Dog class) or that it would growl (because that's what AngryDogs say)? It's an AngryDog, so it should respond accordingly.

(If you wanted all Dogs to react like a base Dog instead of according to their subclass, you could force them to always use the base Dog::speak by changing the $self->speak line to Dog::speak($self), but that's done very rarely, as there are very few cases where it's what you actually want.)

Replies are listed 'Best First'.
Re^2: Overriding methods and Inheritance
by bamaindk (Initiate) on Jan 08, 2008 at 07:19 UTC
    Yes, I can see and understand that logic. I just didn't think that the class I inherited from would know anything about a child. Statically it does not but runtime what is being passed around is as you said an "AngryDog". I was/am confusing static model with the dynamic one.

    So for this to work I need to "morph" AngryDog to a Dog prior to asking SUPER to handle. It might even be reasonable to expect "$self->SUPER" to do this.

    I think I might also have selected the wrong mechanism, as stated in other reply to my question. Delegation seems maybe the better solution. I must admit though it sure did look like the right candidate for inheritance.

    I wonder what happens in this scenario in C++?

    Anyways, thanks for the help:-)

      It might even be reasonable to expect "$self->SUPER" to do this.

      Just to extend my example a little to include that, let's add another method to AngryDog:

      sub pull_tail { $self->SUPER; bite(); }
      In real-world logic, it's obvious that the AngryDog should still growl before biting when its tail is pulled, not bark.

      It's been quite a while since I last used C++, but I talked to a Java junkie friend the last time something like this came up and he confirmed that Java handles it the same as Perl does. I'm pretty sure C++ (and, for that matter, any language that supports polymorphism) would also behave similarly. To do otherwise would render abstract classes/methods pointless. (Derived class overrides the abstract method, base class method calls the abstract method, and... either nothing happens or an exception is thrown unless it calls the derived class's version instead of the base version.)

      But, yeah, I do agree that inheritance looks like an obvious candidate, but dragonchild's AUTOLOAD-based solution is surely both the slickest solution and the one which requires the least code to do what you want.