Re: Overriding new?



On Mar 15, 2010, at 12:07 PM, Tony Arcieri wrote:

On Mon, Mar 15, 2010 at 7:41 AM, Andrea Dallera <andrea@xxxxxxxxxxxxxxxxx>wrote:

Hei Chuck,

that's exactly what i was trying to avoid.


One way to avoid it is to override new. You can use the "allocate" method
to create a new object instance without invoking its constructor. Name the
superclass's "initialize" method something different, like preinitialize,
and invoke that yourself. Be sure to invoke initialize too, if it's
defined.

I've used this approach in frameworks where I intend for users to subclass,
but my general impression nowadays is I should use a lot cleaner base class
that doesn't need these sorts of hax, or not expect users to ever define
their own constructor.

I like Tony's final suggestion. In your base class initialize method, have it make a call to post_initialize. All subclasses should then create a post_initialize method if they need to do any construction (or leave it empty).

This technique is used in Eventmachine since its internals like to control when and how classes are instantiated.

cr


.



Relevant Pages

  • Re: Overriding new?
    ... Also forbidding to specify the constructor would be a way to go but i'd like to allow as much freedom as possible. ... Be sure to invoke initialize too, ... I've used this approach in frameworks where I intend for users to subclass, ... but my general impression nowadays is I should use a lot cleaner base class ...
    (comp.lang.ruby)
  • Re: How come my forms wont resize...
    ... you see by default the form constructor call Initialize() that is ... I went back to my base class form and changed ... > children forms to repsect any parent form property without visiting each ...
    (microsoft.public.dotnet.languages.csharp)
  • Inheritence problem
    ... I have a base class called Animal and in its constructor I initialize a ... int Animal::getY ... try to debug I notice that once it leaves the Animal Constructor, ...
    (alt.comp.lang.learn.c-cpp)
  • RE: ECMA Wrong - Class and Object Initialization Rules - Help!
    ... This is because although the code invokes the default constructor ... it really does not initialize the j variable ... > base class or a different construct for the object's class has been ... > This means in particular that, if a .ctor didn't invoke a base class .ctor ...
    (microsoft.public.dotnet.framework.clr)
  • Re: Confused about line of code in book
    ... >> shortcut to avoid having to call the base class' constructor from the ... how would you call the base constructor from the ... / construct is there to avoid having the developer to call the base class' ...
    (microsoft.public.dotnet.languages.csharp)