Create vs New?
BlitzMax Forums/BlitzMax Beginners Area/Create vs New?
| ||
What does using a Create Function within a Type allow you to do? Is it just a normal function? |
| ||
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. |
| ||
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. |
| ||
To clarify, Create is not a special function. You could call it MerryChristmas if you wanted. |
| ||
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 |
| ||
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. |