in reply to Re: Can a class constructor create an instance of a derived class and return it? Or, can objects transmute into other objects?
in thread Can a class constructor create an instance of a derived class and return it? Or, can objects transmute into other objects?

When I'm doing things like this, I prefer to use a second method aside from new in the parent class to generate the new objects:

sub new { return bless {}, shift; } sub build { my $self = shift; my $sub_obj = Other::Class->new; push @{ $self->{sub_objects} }, $sub_obj; return $sub_obj; }

That way, the other objects can be injected into a parent object for tracking purposes (ie. it provides a list of all other in-use objects of the sub types. Here's a very basic example.

my $parent = Obj->new; my $sub_obj_1 = $parent->build; my $sub_obj_2 = $parent->build; for (@{ $parent->{sub_objects} }){ print $_->name . "\n"; }
  • Comment on Re^2: Can a class constructor create an instance of a derived class and return it? Or, can objects transmute into other objects?
  • Select or Download Code