Casting objects - Polymorphism

BlitzMax Forums/BlitzMax Beginners Area/Casting objects - Polymorphism

The forum is locked. These are the original blitzbasic.com forums, kept so they can still be read. No new topics, replies or edits can be made here. To join in, head over to the Blitz3D+ forums.

just put the list as a global in the type...
SuperStrict

Type TAlien
	Global list:TList = New TList

	Field health:Int = 1
	Field name:String = "Alien"
	'
	
	Method New()
		list.AddLast Self
	End Method
	
	Method PrintHealth() 
		Print "Health in "+name+" = "+health
	End Method
End Type

Type TAlienSmall Extends TALien
	Method New()
		health = 2
		name = "AlienSmall"
	End Method
End Type

Type TAlienBig Extends TAlien
	Method New()
		health = 3
		name = "AlienBig"
	End Method
End Type

' Main
New TAlien
New TAlienSmall
New TAlienBig

For Local alien:TAlien = EachIn TAlien.list
	alien.PrintHealth
	Print alien.health
Next

but you also want to add create functions and remove methods. you want remove methods for sure because we -very- much want to store the TLink so we can quickly remove the item from the list when dead. here I'll add the remove methods...
SuperStrict

Type TAlien
	Global list	:TList = New TList

	Field link	:TLink
	Field health	:Int = 1
	Field name	:String = "Alien"
	'
	
	Method New()
		link = list.AddLast(Self)
	End Method
	
	Method Remove()
		link.Remove
	End Method
	
	Method PrintHealth() 
		Print "Health in "+name+" = "+health
	End Method
End Type

Type TAlienSmall Extends TALien
	Method New()
		health = 2
		name = "AlienSmall"
	End Method
	
	Method Remove()
		Super.Remove
	End Method

End Type

Type TAlienBig Extends TAlien
	Method New()
		health = 3
		name = "AlienBig"
	End Method
	
	Method Remove()
		Super.Remove
	End Method

End Type

' Main
New TAlien
New TAlienSmall
New TAlienBig

For Local alien:TAlien = EachIn TAlien.list
	alien.PrintHealth
	Print alien.health
	If alien.health = 2 Then alien.Remove
Next

Print "-- after remove --"
For Local alien:TAlien = EachIn TAlien.list
	alien.PrintHealth
	Print alien.health
Next

in the example above I only put a remove method in the base type but you should get in the habit of having a remove method in each and every type for any cleanup that -might- need to be done.

in the extend types the remove method should clean up anything that it needs to and then call "super.Remove" to run the base remove method.

[EDIT] I added all the remove methods just to be clear... you don't need them in this example but it's just a better habit to get into.