CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 14 of 14
  1. #1
    Join Date
    Mar 2007
    Location
    Argentina
    Posts
    579

    Calling some code after new?

    Is there any way to run code after .new() constructor?

    I need to write an MustInheritable class, and run code after .New()
    The inherited class cannot call MyBase.New(), because .NET forces to call MyBase.New only as the first line on the .New() constructor, and I need it to run After new(), not before.
    [Vb.NET 2008 (ex Express)]

  2. #2
    Join Date
    Feb 2007
    Location
    Craiova, Romania
    Posts
    326

    Re: Calling some code after new?

    Create a method in the abstract class and call that method in it's constructor. Or make the method MustInherit (pure virtual) and provide specific implementations in subclasses and still, call it in the abstract class constructor.

    Regards

  3. #3
    Join Date
    Mar 2007
    Location
    Argentina
    Posts
    579

    Re: Calling some code after new?

    Quote Originally Posted by marceln View Post
    Create a method in the abstract class and call that method in it's constructor. Or make the method MustInherit (pure virtual) and provide specific implementations in subclasses and still, call it in the abstract class constructor....
    I think you mean this:
    Code:
        Sub Main()
            Dim Something As New Child("MyParameter")
        End Sub
    
        MustInherit Class BaseClass
           
            MustOverride Sub Initializator()
    
            Protected Sub New()
                Initializator()
                AfterNew()
             End Sub
    
            Private Sub AfterNew()
            End Sub
        End Class 'BaseClass
    
        Class Child
            Inherits BaseClass
    
            Public Overrides Sub Initializator()
            End Sub
    
            Public Sub New(ByVal Parameter As Object)
            End Sub
    
        End Class 'Child
    The problem is, I don't know the parameters of Children class. So Initializator cannot access the parameters.

    The better way around it, I had though, is this:
    Code:
        Sub Main()
            Dim Something As New Child(New Child.ChildrenParameters)
            Dim another As New ChildLess
        End Sub
    
        MustInherit Class BaseClass(Of ParametersType)
    
            MustOverride Sub Initializator(ByRef Things As ParametersType)
           
            Protected Sub New(ByRef Things As ParametersType)  'For Child Instances
                Initializator(Things)
                AfterNew()
            End Sub
    
            Protected Sub New() 'For ChildLess
                Initializator(Nothing)
                AfterNew()
            End Sub
    
            Private Sub AfterNew()
            End Sub
        End Class 'BaseClass
    
        Class Child
            Inherits BaseClass(Of ChildrenParameters)
            Public Class ChildrenParameters
            End Class
    
            Overrides Sub Initializator(ByRef Things As ChildrenParameters)
            End Sub
    
            Public Sub New(ByRef Things As ChildrenParameters)
                MyBase.new(Things)
            End Sub
        End Class 'Child
    
        Class ChildLess
            Inherits BaseClass(Of ThisIsUnnecesary)
            Public Class ThisIsUnnecesary
            End Class
    
            Overrides Sub Initializator(ByRef Dummy As ThisIsUnnecesary)
            End Sub
    
            Public Sub New()
                MyBase.new()
            End Sub
        End Class 'ChildLess
    Although all the Unnecesary red code it make me feel cheap, and not very smart.
    [Vb.NET 2008 (ex Express)]

  4. #4
    Join Date
    Feb 2007
    Location
    Craiova, Romania
    Posts
    326

    Re: Calling some code after new?

    Why not use some kind of lazy initialization + dependency injection and forget about that second method.
    Code:
       Sub Main()
            Dim Something As New Child()
            Something.Parameter1 = "MyParameter"
            Something.Initializator()
        End Sub
    
        MustInherit Class BaseClass
           
            MustOverride Sub Initializator()
    
            Protected Sub New()
                'Initializator()
                'AfterNew()
             End Sub
        End Class 'BaseClass
    
        Class Child
            Inherits BaseClass
    
            Public Overrides Sub Initializator()
            End Sub
    
            Public Sub New()
            End Sub
    
            Public Property Parameter1 as Object
            get...
            set...
            End Property
    
        End Class 'Child

  5. #5
    Join Date
    Feb 2007
    Location
    Craiova, Romania
    Posts
    326

    Re: Calling some code after new?

    You can further enhance this and create an abstract factory object that will give you conceret BaseClass objects based on some input.
    Then you would do the Child initialization in the factory and just return the instance. Should look like:
    Code:
    Dim Something as BaseClass = MyFactory.Create(GetType(Child), arglist);

  6. #6
    Join Date
    Mar 2002
    Location
    St. Petersburg, Florida, USA
    Posts
    12,125

    Re: Calling some code after new?

    I would definately go with the Builder pattern (technically a Factory pattern creates instances, while the Builder pattern creates them - often with a factory, and does significant post creation work)

    Calling virtual methods in the drerived class from the base class is valid, but is definately NOT recommended.

    FYI: If you compile your code with "maximum warnings", and "treat warnings are errors" [IMPO - how ALL code should be compiled without any other options], then that technique will not compile!!!
    TheCPUWizard is a registered trademark, all rights reserved. (If this post was helpful, please RATE it!)
    2008, 2009,2010
    In theory, there is no difference between theory and practice; in practice there is.

    * Join the fight, refuse to respond to posts that contain code outside of [code] ... [/code] tags. See here for instructions
    * How NOT to post a question here
    * Of course you read this carefully before you posted
    * Need homework help? Read this first

  7. #7
    Join Date
    Mar 2007
    Location
    Argentina
    Posts
    579

    Re: Calling some code after new?

    Quote Originally Posted by marceln View Post
    Why not use some kind of lazy initialization + dependency injection and forget about that second method.
    Code:
       Sub Main()
            Dim Something As New Child()
            Something.Parameter1 = "MyParameter"
            Something.Initializator()
        End Sub
    ...
    Thanks for your suggestion.
    The objective is to do hard work in the base class, (which is coded only once), and reduce the work each time someone write an inherited class, or create an instance (which is done much more times).
    If the user need to call Something.Initializator(), is the same than force the user to call AfterNew() in any Child constructor class.
    The user can't forget to write the Sub Initializator(), because is a MustOverride routine, but it can forget to call the AfterNew, because nothing forces him to do it.
    Also, can forget to write Something.Parameter1 = "MyParameter"

    My way of doing it also have a problem. The user need to know than
    Code:
    Initializator(ByRef Things As ChildrenParameters)
    gonna be run with the same parameter instance passed to
    Code:
    Public Sub New(ByRef Things As ChildrenParameters)
    All I can do about it, is add a XML comment to Initializator(), and to New(), although is not very safe the programmer will read it.
    [Vb.NET 2008 (ex Express)]

  8. #8
    Join Date
    Mar 2002
    Location
    St. Petersburg, Florida, USA
    Posts
    12,125

    Re: Calling some code after new?

    The problem with the approach you are taking is that it is "fragile" (easily broken). Remember, when the overridden member in the derived class is called, the derived class constructor will NOT have run, but explicit member initializers will have. This can quickly lead to attempts to access un-initialized variables, which the compiler can NOT detect, resulting in very very "strange" bugs.

    I don't understand why you are rejecting the use of the Builder Pattern.......
    TheCPUWizard is a registered trademark, all rights reserved. (If this post was helpful, please RATE it!)
    2008, 2009,2010
    In theory, there is no difference between theory and practice; in practice there is.

    * Join the fight, refuse to respond to posts that contain code outside of [code] ... [/code] tags. See here for instructions
    * How NOT to post a question here
    * Of course you read this carefully before you posted
    * Need homework help? Read this first

  9. #9
    Join Date
    Mar 2007
    Location
    Argentina
    Posts
    579

    Re: Calling some code after new?

    Quote Originally Posted by marceln View Post
    You can further enhance this and create an abstract factory object that will give you conceret BaseClass objects based on some input. ...
    Quote Originally Posted by TheCPUWizard View Post
    ...
    I don't understand why you are rejecting the use of the Builder Pattern.......
    I are not rejecting it. I are reading about it to understand what is.

    *Doing work*
    [Vb.NET 2008 (ex Express)]

  10. #10
    Join Date
    Mar 2007
    Location
    Argentina
    Posts
    579

    Re: Calling some code after new?

    Quote Originally Posted by TheCPUWizard View Post
    ...Remember, when the overridden member in the derived class is called, the derived class constructor will NOT have run,
    That is the problem. I need to run code After the derived class constructor. Is all I need.
    I was thinking of replacing the derived class constructor whit the MustOverride Initializer().

    The problem is:
    - I cannot block the coding of a New() constructor in the inherited class.
    - There is not fail-safe way to make the user to understand that it need to move his constructor code to Initializer().

    (All that would be easy fixed, if .NET supported an AfterNew constructor)
    [Vb.NET 2008 (ex Express)]

  11. #11
    Join Date
    Mar 2002
    Location
    St. Petersburg, Florida, USA
    Posts
    12,125

    Re: Calling some code after new?

    Quote Originally Posted by Marraco View Post
    I are not rejecting it. I are reading about it to understand what is.

    *Doing work*
    Stupid implementation of Builder Pattern... (assume we have base class B, and derived classes D1, D2, D3
    Code:
    class Builder  // this should be a singleton...
    {
    B CreateInstance(params)
    {
        
        B b = ...// determine appropriate derived class and create instance
        b.Initialize();  // Perform virtual post construction initialization
        return b;
    }
    
    D1 CreateInstatnce(params_That_Mandate_D1)
    {
        D1 d = D1.CreateInstanceForBuilder(params_That_Mandate_D1)
        d.Initialize()
        return d;
    }
    }
    Note that in the second part of the code we used a static member of the class (factory method). This allows making the constructor non-public, and preventing accidental creation of instances that bypass the builder.
    TheCPUWizard is a registered trademark, all rights reserved. (If this post was helpful, please RATE it!)
    2008, 2009,2010
    In theory, there is no difference between theory and practice; in practice there is.

    * Join the fight, refuse to respond to posts that contain code outside of [code] ... [/code] tags. See here for instructions
    * How NOT to post a question here
    * Of course you read this carefully before you posted
    * Need homework help? Read this first

  12. #12
    Join Date
    Mar 2007
    Location
    Argentina
    Posts
    579

    Re: Calling some code after new?

    Quote Originally Posted by marceln View Post
    ... and create an abstract factory object...
    Quote Originally Posted by TheCPUWizard View Post
    I would definately go with the Builder pattern ...
    Wow. It never had occurred to me to search the word Pattern.

    I have found some of them, and I see, I have reinvented the wheel many times. (and some where square wheels )

    I was on the wrong path (I mean pattern )

    [Vb.NET 2008 (ex Express)]

  13. #13
    Join Date
    Mar 2002
    Location
    St. Petersburg, Florida, USA
    Posts
    12,125

    Re: Calling some code after new?

    Quote Originally Posted by Marraco View Post
    Wow. It never had occurred to me to search the word Pattern.

    I have found some of them, and I see, I have reinvented the wheel many times. (and some where square wheels )

    I was on the wrong path (I mean pattern )


    Been living under a rock? \

    Nearly every employeer would expect at leads a basic knowledge of the Patterns covered in this book. Many of them are covered in nearly every text/tutorial book....

    This article is about the book by Gamma et al. For other uses, see design pattern.
    Design Patterns: Elements of Reusable Object-Oriented Software (ISBN 0-201-63361-2) is a software engineering book describing recurring solutions to common problems in software design. The book's authors are Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides with a foreword by Grady Booch. They are often referred to as the GoF, or Gang of Four. The book is divided into two parts, with the first two chapters exploring the capabilities and pitfalls of object-oriented programming, and the remaining chapters describing 23 classic software design patterns. The book includes examples in C++ and Smalltalk. It won a Jolt productivity award in 1994. [1]

    The original publication date of the book was October 21, 1994 with a 1995 copyright, and as of April 2007, the book was in its 36th printing. The book was first made available to the public at OOPSLA meeting held in Portland, Oregon in October 1994. It has been highly influential to the field of software engineering and is regarded as an important source for object-oriented design theory and practice. More than 500,000 copies have been sold in English and in 13 other languages.
    TheCPUWizard is a registered trademark, all rights reserved. (If this post was helpful, please RATE it!)
    2008, 2009,2010
    In theory, there is no difference between theory and practice; in practice there is.

    * Join the fight, refuse to respond to posts that contain code outside of [code] ... [/code] tags. See here for instructions
    * How NOT to post a question here
    * Of course you read this carefully before you posted
    * Need homework help? Read this first

  14. #14
    Join Date
    Mar 2007
    Location
    Argentina
    Posts
    579

    Re: Calling some code after new?

    Quote Originally Posted by TheCPUWizard View Post
    Been living under a rock? \

    Nearly every employeer would expect at leads a basic knowledge of the Patterns covered in this book. Many of them are covered in nearly every text/tutorial book....
    I'm not a professional. Just third world, underground geek.
    [Vb.NET 2008 (ex Express)]

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured