Constructor Overloading?

Monkey Forums/Monkey Programming/Constructor Overloading?

therevills(Posted 2011) [#1]
Can you do this in Monkey somehow?

Class Level
	Field level:Int
	Field round:Int

	Method New()
		Self(1, 1)
	End

	Method New(level:Int, round:Int)
		Self.level = level
		Self.round = round
	End
End


Ive tried the above and get "Expression cannot be invoked."

With Java you would call "this(1, 1)"...

Just checking to see if Ive missed anything...


Fishy(Posted 2011) [#2]
I think it was Self.New(1, 1) if I recall correctly.

EDIT: Default values are possible in arguments as well so:

Method New(arg1:Int=1, arg2:Int=1)
    ' Bla bla bla
End



therevills(Posted 2011) [#3]
I think it was Self.New(1, 1) if I recall correctly.


Ive tried that, but still get an error (Syntax error):


Function Main()
	New Level(1,1)	
End

Class Level
	Field level:Int
	Field round:Int
	
	Method New()
		Self.New(1, 1) ' <---- Syntax error
	End
	
	Method New(l:Int, r:Int)
		Self.level = l
		Self.round = r
	End
	
End



Fishy(Posted 2011) [#4]
Sorry, I was confusing this with "Super.New". Strange that Self.New does not work the same way.

In this case default arguments is the only work around I know about, though less than ideal in some situations.

Function Main()
	New Level()	 ' No args, defaults to (1, 1)
End

Class Level
	Field level:Int
	Field round:Int
	
	Method New(l:Int=1, r:Int=1)
		Self.level = l
		Self.round = r
	End
	
End


Hopefully someone else has the answer you are looking for. :)


therevills(Posted 2011) [#5]
Yeah looks like default arguments is the only way to do it... Thanks!


MikeHart(Posted 2011) [#6]
I use constructor overloading too. But I don't have a default one without parameters.

Class sprite
	
	  Field image:Image	
	
	  Field xPos:Float = 0.0		
	  Field yPos:Float = 0.0		
	
	
	  '-----------------------------------------------------------------------------
	  Method New (atl:Image, xp:Int, yp:Int, w:Int, h:Int, startX:Float, startY:Float )
			xPos = startX
			yPos = startY
			image = atl.GrabImage( xp,yp,w,h,1,Image.MidHandle )
	  End
	
	  '-----------------------------------------------------------------------------
	  Method New (fname:String, startX:Float, startY:Float )
			xPos = startX
			yPos = startY
			image = LoadImage (fname, 1, Image.MidHandle)
	  End