Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris

Re: How do I make a constructor?

by jdhedden (Deacon)
on Jul 05, 2005 at 19:49 UTC ( #472581=note: print w/replies, xml ) Need Help??

in reply to How do I make a constructor?

I'm a pragmatist, and see nothing wrong with supporting $obj->new(). In fact, perlobj even mentions it. If your class takes args that are in addition to what the parent class uses in ->new(), then you need a bit more code.
# Create a new object sub new { my $thing = shift; my $class = ref($thing) || $thing; my $self = {}; bless($self, $class) if (! $self->_init($thing, @_)) { # Failed to initialize # Throw some sort of error, or return; # Returns 'undef' } return ($self); } # Initialize a new object sub _init { my $self = shift; my $thing = shift; # Separate '@_' into args for parent class and args for this sub +class my @parent_args = ...; my @my_args = ...; # Perform parent class initialization if (! $self->SUPER::_init($thing, @parent_args)) { # Parent class initialization failed return (0); } # Perform subclass initialization # Making use of '@my_args', if any if (ref($thing)) { # $thing->new( ... ) was called # Make use of '@my_args', if any # And make use of object's data, if applicable } else { # CLASS->new( ... ) was called # Make use of '@my_args', if any } return (1); }
Note that $thing is passed to _init() in addition to the args (cf. jamesduncan's code above). When the user calls $obj->new(), this allows the initialization method to make use of data contained in the calling object, if that is applicable to your code.

Replies are listed 'Best First'.
Re: Answer: How do I make a constructor?
by tlm (Prior) on Jul 06, 2005 at 03:46 UTC

    Why the separate _init method?

    the lowliest monk

      I do this same thing with the _init(). Basically I can use an inheritence and the constructor remains the same, the _init method can change with each child object. It just seems to keep things organized.


      Edit by castaway: Closed small tag in signature

Log In?

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

How do I use this? | Other CB clients
Other Users?
Others studying the Monastery: (2)
As of 2021-10-19 22:51 GMT
Find Nodes?
    Voting Booth?
    My first memorable Perl project was:

    Results (77 votes). Check out past polls.