Difference Between New() and OnCreate()
Monkey Forums/Monkey Programming/Difference Between New() and OnCreate()
| ||
Is there a difference? Obviously, there is... I can't do something like [monkeycode] x = New y("1") [/monkeycode] unless I have a New(s:String) method defined, even if I have an OnCreate(s:String) method defined. If I never use parameters for creating new y objects, then I don't need New(), and OnCreate() triggers as well. I think. |
| ||
Within your OnCreate method you would have to call "New" and return the object: [monkeycode]x = y.OnCreate("1") ... Class y Field str:String Function OnCreate:y(s:String) local o:y = New y o.str = s Return o End End[/monkeycode] With using the constructor ("new") you can replace most of that code: [monkeycode]x = New y("1") ... Class y Field str:String Method New(s:String) self.str = s End End[/monkeycode] |
| ||
OnCreate is just a method on the App class. It's not called when a class is instantiated. |
| ||
Interesting. Thanks, guys. Are there any general rules as to when to use New/OnCreate and when not to? |
| ||
Use OnCreate() callback for your application, use New() for instantiating your objects. Unless you want to wrap New() with OnCreate() for some reason ? I don't get it. |
| ||
When I first read CK's post I thought he was talking about the "old" BlitzMax way to get around the lack of parameterised constructors... but now I am now so sure. The "old" BlitzMax way was just to have a function (which I normally called "Create") to instante the object: [bbcode]Type Sprite Field x:Int Field y:Int Function Create:Sprite(x:Int, y:Int) Local s:Sprite = New Sprite s.x = x s.y = y Return s End Function End Type[/bbcode] |
| ||
There aren't any hard and fast rules about whether to initialise everything in New() or use an initialisation function (which might be called OnCreate() or Init() or whatever you want). If you have multiple constructors many of which do similar things, an initialisation function for the common behaviours is useful. As for why one doesn't overload New() for App-derived classes, I suspect the main reason Mark did it this way is to avoid people making mistakes by failing to call the super class constructor at the start of their own constructor. If there is some time-dependent initialisation needed on some targets this could also be allowed for. |