in reply to OOP and derived classes

In Perl when you create a new derived class should you explicitly create a base instance inside the derived class constructor?
Here's a simple answer: yes, you should. You don't get 'base instance' automatically.

Longer version: I don't know Java, but I suppose Java's object is (a pointer to) a struct-like thing, and a derived class appends its part (instance variables or whatever Java calls them) to the 'base part'. OTOH, Perl's object is (a reference to) anything at all. For example, a string, a number, array, hash, function... There is no 'base instance' and 'derived instance', just 'instance'. Here's a function object:

$ perl -E 'sub method { my $self = shift; $self->() } my $obj = sub { say "HELLO" }; bless $obj; $obj->method()' HELLO

Replies are listed 'Best First'.
Re^2: OOP and derived classes
by Anonymous Monk on Feb 14, 2015 at 20:04 UTC
    >Here's a simple answer: yes, you should. You don't get 'base >instance' automatically.

    but it's looks like its optional in Perl? what happens when the base class is not instantiated and I call a base class method which accesses some base class properties ,through a derived object ? will the method be called as a base class method or will it be called as a derived one (the first parameter sent to the method would be a base object or a derived one?

      but it's looks like its optional in Perl?
      Yes.
      what happens when the base class is not instantiated and I call a base class method which accesses some base class properties ,through a derived object ?
      If, say, the object in question is a hash, then base class will find undef instead of whatever it wanted to find, like with all other hashes.
      will the method be called as a base class method or will it be called as a derived one (the first parameter sent to the method would be a base object or a derived one?
      The base class will get the whole thing, 100% of it. So, in Java's terms, the base method will get the derived object.
        So can I call a derived method with a base object,like can I use a base object in place of a derived object,for example when a method expects the derived class but I do pass the base class instead?