Method New Parameters

BlitzMax Forums/BlitzMax Programming/Method New Parameters

BLaBZ(Posted 2010) [#1]
Is there a way to pass parameters through the new method of an object?

ex:
Type TTest 

	Field Name:String
	
	Method New(Name:String)
		Self.Name = Name 
	End Method 
	
End Type 


Local aTest:TTest = New TTest



_JIM(Posted 2010) [#2]
Sadly, no.

I use an aditional "Init" method for this stuff. Also, I use the "New" method to create TLists and such, not to configure the new created instance.


Volker(Posted 2010) [#3]
Type TTest

	Field Name:String
	
	Method Create:TTest(Name:String)
		Self.Name = Name 
		Return Self
	End Method 
	
End Type 


Local aTest:TTest = New TTest.Create("a name")





Jesse(Posted 2010) [#4]
you don't need to use new in the declaration:
Local aTest:TTest = TTest.Create("a name")



Jasu(Posted 2010) [#5]
Yes you do because Create is a method, not a function.


Jesse(Posted 2010) [#6]
you are right. my fault.
But why would you want to make it a method?
if you make it a function you wouldn't need to add "New".
to me it seems to be creating an instance of ttest at the line and calling the method to create another instance of it.
the same as this:
Local aTest:TTest = (New TTest).Create("a name")

which is somewhat redundant.


Czar Flavius(Posted 2010) [#7]
If you inherit objects, they will call all their News in order. However, New can't take any parameters, and Create as a function will create a new object, so you can't use a base type's create to finish setting up a derived type which you just created using its own create function.

As a method, you can "chain" the creates, however. There is no redundant creation of objects too.

Strict

Type TBase
    Field top:String
    
    Method Create:TBase(init:String)
        top = init
        Return Self
    End Method
End Type

Type TDerived Extends TBase
    Field bottom:String
    
    Method sub_create:TDerived(more_init:String)
        bottom = more_init
        Return Self
    End Method
End Type

Local something:TBase = New TDerived.sub_create("I am bottom").Create("I am top")


This particular example has the oddity that the derived create is called before the base one. In many cases the order won't matter (but not all).

It would be a bit more tricky to do this using create functions. Derived create methods should be given a unique name (edit: compared to the base type's create method). Personally I prefer the function way, but sometimes I have no choice but to use the method way.


Jesse(Posted 2010) [#8]
wow! I just learned something new. I guess That is what happens when one never went to school for things like this.


Czar Flavius(Posted 2010) [#9]
Don't worry, I learnt more about programming on these forums and with BlitzMax than I ever did at university.