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

Can a class constructor create an instance of a derived class and return it? Or, can objects transmute into other objects?
Yes, and yes. As long as you document it properly, it's fine. Re-blessing already-blessed objects is a little bit sketchy, but if you know what you're doing, go ahead (that's actually how subclass constructors work in C++). I would tend to write SNMPObject::CiscoStack->new(...) instead of SNMPObject::CiscoStack::new(...) in the superclass constructor, though.
  • Comment on Re: Can a class constructor create an instance of a derived class and return it? Or, can objects transmute into other objects?

Replies are listed 'Best First'.
Re^2: Can a class constructor create an instance of a derived class and return it? Or, can objects transmute into other objects?
by stevieb (Canon) on Sep 28, 2017 at 15:52 UTC

    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"; }