the new method

BlitzMax Forums/BlitzMax Beginners Area/the new method

yossi(Posted 2014) [#1]
if I understand right the new method when override is a kind of constructor such as exists in a other oop programing language like c#,c++,java,delphi and monkey but when I try to declare parameters in the new method I get an error (without parameters it works fine).

what is the purpose of the new method if it can not get parameters ?


GfK(Posted 2014) [#2]
You can use it if you want to set default parameters automatically on creation of the object:
Local a:myType = New MyType
Print a.x

Type myType 
  Field x:Int

  Method New()
    Self.x = 10
  End Method
End Type


To pass parameters:
Local a:myType = myType.Create(10)
Print a.x

Type myType 
  Field x:Int

  Function Create:myType(x:Int)
    Local t:myType = New MyType
    t.x = x
    Return t
  End Function
End Type



yossi(Posted 2014) [#3]
thank you.


H&K(Posted 2014) [#4]
Also, if you wanted to include each instance in a list of instances of that object. (Like B3D)
Then you can call your addObjectToList() method from new and make that effectively automatic.
You are obviously swapping ease of programming for performance, but if you only needed the list for debug builds then a nice little ?debug block solves that.


col(Posted 2014) [#5]
Just for a little clarity as for sure you will ask about this in the future ( everybody does :D )...


In GfKs example the 'Function within the type', the Function call doesn't know about any Types members of the Type it appears in, the function is a 'separate entity' to the Type and only appears within the Type scope as far syntax is concerned. So if you tried to use x varaible within the function you will get an error of an unknown variable. However, you'll notice in the function that the New MyType is created there as the variable 't'. Then the members variable x is set using the instance of 't' and that instance is returned. There is another way using a similar 'Create' Method instead of Function. This still means that you need to create a 'New' instance before you use the 'Method' call and BlitzMax still allows you to do this in a one line statement so that you can create a new instance and call a method within that new instance and pass parameters to the method all in one go. In the same example and using this stlye you will need to return 'Self' from the Create Method to return the new instance back to the 'a' variable...

An example :-

Local a:myType = New myType.Create(10)
Print a.x

Type myType 
  Field x:Int

  Method Create:myType(xx:Int)
    x = xx
    Return Self
  End Method
End Type


I suppose whether you use one way or the other is just how you prefer to write your own code for readability, but it's nice to know other ways of how it can be done.