Call extended type method from base type instance

BlitzMax Forums/BlitzMax Programming/Call extended type method from base type instance

What ??? ..
Well if you want to create a base type, and extend sub objects from that type.. you will start to run in to some problems when you want to return an extended type as its base type.

An example of what I mean: You have a gui gadget type, called "guigadget". Now this stores the x,y,width,height and lets any other features for a particular gadget (button,scrollbar,textbox,etc) upto the extended type. Now say we create and return a guigadget, but it is actualy guigadget_button type. How would you then call any methods from the extended type ?

Take a look at this code, it might help. This seems like the most viable way to me, but unless Im missing something. Is there a more suitable way of doing this ?

Type fruit
	Field x,y,width,height
	Field _CallUpdate(f:fruit)
	
	Method Update()
		'because the base class update is called, we need to use the method caller stored
		_CallUpdate(Self)
	End Method
End Type

Type apple Extends fruit
	Field brand:String
	
	'creation function
	Function Create:fruit(x,y,width,height,brand:String)
		Local a:apple = New apple
		'setup properties
		a.x = x
		a.y = y
		a.width = width
		a.height = height
		a.brand = brand
		'setup class callers
		a._CallUpdate = apple.CallUpdate
		
		Return a
	End Function
	
	'callers for this class
	Function CallUpdate(f:fruit)
		apple(f).Update()
	End Function
	
	'methods for this class
	Method Update()
		Print "update apple, brand = "+brand
	End Method
End Type

Type grape Extends fruit
	Field numberinbunch
	
	'creation function
	Function Create:fruit(x,y,width,height,bunch)
		Local g:grape = New grape
		'setup properties
		g.x = x
		g.y = y
		g.width = width
		g.height = height
		g.numberinbunch = bunch
		'setup class callers
		g._CallUpdate = grape.CallUpdate
		
		Return g
	End Function
	
	'callers for this class
	Function CallUpdate(f:fruit)
		grape(f).Update()
	End Function
	
	'methods for this class
	Method Update()
		Print "update grape, number in bunch = "+numberinbunch
	End Method
End Type

'now we can create 1 apple and 1 grape, and return them as the base class.
'if we want to call the update function for either, we can, because it has been mapped using a function pointer.
Local fruit1:fruit = apple.Create(0,0,60,60, "golden smith")
Local fruit2:fruit = grape.Create(10,10,60,100, 75)

fruit1.Update()
fruit2.Update()

Input "press enter to end"