Access derrived field from base type?

BlitzMax Forums/BlitzMax Beginners Area/Access derrived field from base type?

Danny(Posted 2010) [#1]
Hi All,

Is it possible to access a derived type's field from the base type, as illustrated in the example below? I mean, without adding an abstract field to the base type.

Type Gadget
	Field _aha
End Type

Type ListBox Extends Gadget
	Field _item$
	Function createLB:ListBox()
		Return New Listbox
	End Function
End Type

Function CreateListBox:ListBox()
	Return ListBox.CreateLB()
End Function

Thing:Gadget = CreateListBox()

Thing._item$ = "This not gonna work!"

DebugStop
End


Or is perhaps my general approach incorrect how I create and return types? Yes, I know I could do a "Thing:ListBox = CreateListBox()" but the above is just an illustration of 'general functions' I'd like to make that handle any base type - but by exception are able to access the derived type fields - or methods for that matter!


Cheers,

Danny


Who was John Galt?(Posted 2010) [#2]
You can substitute a derrived type where a base class is expected. Try doing an explicit cast to gadget on the result of CreateListBox. You have to cast back to the derived type to access the derived fields, and I presume the cast will return NULL if you attempt to cast the wrong type. Give it a whirl.


matibee(Posted 2010) [#3]
You can cast "Thing" into a listbox type like this:

ListBox(Thing)._item$ = "This is gonna work!"


And as John says if you try casting to an unrelated type the cast fails.

Personally I don't like downcasting. Make "Thing" a ListBox to start with and it will work anywhere a Gadget type is required as well as anywhere a ListBox is required.




Danny(Posted 2010) [#4]
Yes I can imagine the dangers of downcasting, but it should be easy to prevent that - eg. by adding a 'GadgetType' field to the Gadget Type so each derived type can be identified for what it is before poking into it.

Thanks for the examples and explanations guys!

Danny.