Create vs New?

BlitzMax Forums/BlitzMax Beginners Area/Create vs New?

BLaBZ(Posted 2010) [#1]
What does using a Create Function within a Type allow you to do?

Is it just a normal function?


TomToad(Posted 2010) [#2]
Create will let you pass parameters when creating an instance of the type.

Example using new
Type TPixel
    Field X:int
    Field Y:Int

    Method New()
        X = 10
        Y = 10
    End Method
End Type

Local Pixel:TPixel = New TPixel 'Good if I want x,y to be 10,10
Pixel.X = 15 'Otherwise, I need to manually set it up
Pixel.Y = 20 'Or create a setter method to do it

As you can see, New will allow you to initialize to default values, but not allow you to specify new values when you create the instance.

Example with Create()
Type TPixel
    Field X:int
    Field Y:Int

    Function Create:TPixel(X:Int,Y:Int)
        Local Pixel:TPIxel = New TPixel
        Pixel.X = X
        Pixel.Y = Y
        Return Pixel
    End Function
End Type

Local Pixel:TPixel = TPixel.Create(15,20) 'Now we can initialize with the values we want.



_Skully(Posted 2010) [#3]
Yes, a Create function is just a standard function.

New on the other hand runs each time a type is instanciated but does not accept any parameters.


Czar Flavius(Posted 2010) [#4]
To clarify, Create is not a special function. You could call it MerryChristmas if you wanted.


H&K(Posted 2010) [#5]
Some ppl (well me) say that NEW shouldn't appear in open code, and in fact should be restricted to only existing in your "create" (or MerryChristmas) Function


Czar Flavius(Posted 2010) [#6]
That's a good rule most of the time, but it's important to understand why. I use New for things like TLists often but for custom types I've often found myself needing creation parameters and having to go back and changing code, so it's good practice to use them from the beginning, unless it's a very simple type and always will be.