Beefy Boxes and Bandwidth Generously Provided by pair Networks
Come for the quick hacks, stay for the epiphanies.
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??
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.

In reply to Re: How do I make a constructor? by jdhedden
in thread How do I make a constructor? by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others musing on the Monastery: (7)
As of 2024-04-23 16:54 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found