Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

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

by Anonymous Monk
on Sep 28, 2017 at 15:43 UTC ( [id://1200283]=note: print w/replies, xml ) Need Help??


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

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1200283]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others chilling in the Monastery: (4)
As of 2024-04-19 06:11 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found