Call extended type method from base type instance

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

If you don't have a virtual method in the base type - say when different derived types will implement different methods - then you can check what type the instance is, cast to the proper sub-type and then invoke the method.

Strict

Type Fruit
	Method whatAmI() Abstract
End Type

Type Apple Extends Fruit
	Method whatAmI()
		Print "I am an apple"
	End Method

	Method howManyWorms()
		Print "Only a couple of worms"
	End Method
End Type

Type Orange Extends Fruit
	Method whatAmI()
		Print "I am an orange"
	End Method

	Method howJuicy()
		Print "Very juicy"
	End Method
End Type

Local fruit1:Fruit=New Apple
Local fruit2:Fruit=New Orange

PrintInfo(fruit1)
PrintInfo(fruit2)

Function PrintInfo(thing:Fruit)

	thing.whatAmI()
	
	If Apple(thing)
		Local myApple:Apple = Apple(thing)
		myApple.howManyWorms
	Else
		Local myOrange:Orange = Orange(thing)
		myOrange.howJuicy()
	EndIf
		
End Function