Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?
 
PerlMonks  

Answer: How do I make a constructor?

( #472581=categorized answer: print w/ replies, xml ) Need Help??

Q&A > object-oriented programming > How do I make a constructor? 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.

Comment on Answer: How do I make a constructor?
Download Code
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.

      Don
      WHITEPAGES.COM | INC

      Edit by castaway: Closed small tag in signature

Log In?
Username:
Password:

What's my password?
Create A New User
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others chanting in the Monastery: (18)
As of 2014-07-14 13:13 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    When choosing user names for websites, I prefer to use:








    Results (260 votes), past polls