That would be a silly and confusing definition. If you had:
sub foo {
my $x = bless [], "X";
my $y = bless {}, "Y";
...
return 1;
}
Is that a double constructor? Half a constructor? | [reply] [Watch: Dir/Any] [d/l] |
bless attaches a method dispatch table to some Perl data structure. That's not what most people would consider a constructor.
In most programming languages the constructor is some function that gets called once the object has been allocated in memory in order to have its attributes initialized. Setting its method dispatching table is something done by the language runtime under the hood, not inside the constructor.
Perl leaves to the programmer the task of allocating the object storage, setting the dispatch table and initializing the object for greater flexibility.
In my opinion, a constructor in Perl can be any function or code fragment returning a new object in an usable state. For some simple cases, just a bless {}, $class can qualify as such, but the usual thing is to use a method for that and to call it "new".
| [reply] [Watch: Dir/Any] [d/l] |
package Colour;
sub new {bless {colour => $_[1]}, $_[0]}
sub colour {$_[0]{colour}}
package Age;
sub new {bless {age => $_[1]}, $_[0]}}
sub age {$_[0]{age}}
Whee. Now I can make colour objects, and age objects:
use Colour;
use Age;
my $c_obj = Colour::->new("orange");
my $a_obj = Age::->new(42);
print "I have an object with colour ", $c_obj->colour;
print "And another object aged ", $a_obj->age;
Goodie. Now, if there was any flexibility, I'd be able to create a class that's both, using multiple inheritance, and without breaking encapsulation (that is, peeking and making use of the implementation of a parent class):
package Age_and_Colour;
use Age;
use Colour;
our @ISA = qw[Age Colour];
sub new {
my ($class, $age, $colour) = @_:
... Now what? ...
}
If I call Age::->new, I get back an object initialized with an age, but no colour; but if I call Colour::->new, I get one with a colour, but no age.
Greater flexibility is fine, but if this requires a lot more effort from the programmer, it's pointless. That's like saying C has greater flexibility when it comes to regular expressions: it gives you a minimal string implementation, and leaves everything else to the programmer. Sure, you *can* make more fantastic regular expressions in C than in Perl, but I don't see many people actually doing that.
(cue the Pavlov reactions: "but you shouldn't use MI anyway") | [reply] [Watch: Dir/Any] [d/l] [select] |
Well, if I had to, I'd name it a multiple constructor. I would find it a "silly and confusing" way to do things ;).
I read that definition in the Perl documentation by the way.
| [reply] [Watch: Dir/Any] |
| [reply] [Watch: Dir/Any] |