Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw

Answer: How do I make a constructor?

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

Q&A > object-oriented programming > How do I make a constructor? - Answer contributed by jdhedden

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
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (9)
As of 2016-10-25 08:46 GMT
Find Nodes?
    Voting Booth?
    How many different varieties (color, size, etc) of socks do you have in your sock drawer?

    Results (315 votes). Check out past polls.