Constructors

BlitzMax Forums/BlitzMax Programming/Constructors

Czar Flavius(Posted 2010) [#1]
Before I was using this way
Type TPerson
	Field _name:String
	
	Function Create:TPerson(name:String)
		Local person:TPerson = New TPerson
		person._name = name
		Return person
	End function
End Type


And if I extended it, no problem

Type TWorker Extends TPerson
	Field _business:String
	
	Function Create:TWorker(name:String, business:String)
		Local worker:TWorker = New TWorker
		worker._name = name
		worker._business = business
		Return worker
	End Function
End Type


But then I changed to this way, as it looked cooler

Type TPerson
	Field _name:String
	
	Method Create:TPerson(name:String)
		_name = name
		Return Self
	End Method
End Type


But now I can't extend if I need more parameters!

Type TWorker Extends TPerson
	Field _business:String
	
	Method Create:TWorker(name:String, business:String)
		_name = name
		_business = business
		Return Self
	End Method
End Type


Wrong return type and wrong parameters to extend. Returning TPerson instead of TWorker is annoying but ok. But I have to create another construction method, which seems inelegant, and leaves the old one dangling around.

Any suggestions?


GfK(Posted 2010) [#2]
Use the non-cool-looking way.


Htbaa(Posted 2010) [#3]
Overloading isn't supported.


Czar Flavius(Posted 2010) [#4]
The reason why I ask is I want extended types to use their base's constructor too, to avoid repeating code. Here's a real example

Type TProjection Extends TResourceTable
	Method Create2:TProjection(consider_length, base_resources:TBundle)
		Super.Create(0, consider_length)
		_base_resources = base_resources
		For Local b:TBundle = EachIn _time_table
			b.gain_from(_base_resources)
		Next
		Return Self
	End Method

Type TResourceTable
	Method Create:TResourceTable(start_turn, consider_length)
		_turn_offset = start_turn
		_turns_to_consider = consider_length
		_time_table = New TBundle[_turns_to_consider]
		For Local i = 0 Until _time_table.Length
			_time_table[i] = TBundle.Create()
		Next
		Return Self
	End Method



Htbaa(Posted 2010) [#5]
It sure would be nice indeed but overloading isn't supported.


Czar Flavius(Posted 2010) [#6]
I'm aware overloading isn't supported, that's why I'm asking for (alternative) suggestions..


plash(Posted 2010) [#7]
It seems you want to call Create for each type individually. If, however, you're extending a type that uses a base creation method, I would suggest using an 'init' method in the base type(s), and have the extending types call that from their Create method (or not).

But it seems you don't want to do it this way.


Czar Flavius(Posted 2010) [#8]
I could do that with a Create function but not method, unless I give the methods unique names for each type (but then I might as well not use an init method, like in my code above)