Type Constructors?

BlitzMax Forums/BlitzMax Programming/Type Constructors?

Twinprogrammer(Posted 2012) [#1]
Hey Guys,

I was wondering if you can create a constructor for types(like if you can use a method to define fields), and if you can, how to make one.

Twinprogrammer


Yasha(Posted 2012) [#2]
Not sure quite what you mean by the question, but constructors are defined thusly:

Type foo
    Field a:Int, b:Int
    Method New()
        a = 10; b = 20
    End Method
End Type


Every time you create a foo with "New foo", the a field will have a value of 10 and the b field one of 20. "New" can contain arbitrary code, but cannot be defined to take parameters: if you want parameters, you need to use a static method:

Type foo
    Field a:Int, b:Int
    Function Make(a:Int, b:Int)
        Local f:Foo = New foo
        f.a = a; f.b = b
        Return f
    End Function
End Type


Now you can get a new foo with the values 42 and 47 in a and b respectively by calling foo.Make(42, 47). This isn't a formal constructor with any kind of built-in language recognition, though - it's just a design pattern. It also doesn't play well if foo is extended - the subclass will need to reimplement Make, or it will not return objects of the right type; and the overriding Make method is limited to the same type signature as the original (still typed to return foo objects, still taking precisely two integers).


Jesse(Posted 2012) [#3]
maybe something like this:

Type foo
   Field a:Int, b:Int
   Method Make:foo(a:Int,b:Int)
       Self.a = a
       Self.b = b
	  Return Self
   End Method
End Type

Local f:foo = New foo.Make(42,47)
Print f.a+" "+f.b

Type bar Extends foo
	Method make:bar(a:Int,b:Int)
		Self.a = a
		Self.b = b
		Return Self
	End Method
End Type

Local b:bar = New bar.Make(40,20)
Print b.a+"  "+b.b



Twinprogrammer(Posted 2012) [#4]
Cool, thanks !

Last edited 2012


ProfJake(Posted 2012) [#5]
Just as a side note: the "standard" way of doing this in BlitzMax is naming the function Create (note Make).
So when other people read your code they immediately know what's going on.

Works either way.

Last edited 2012