Overriding Create()

BlitzMax Forums/BlitzMax Beginners Area/Overriding Create()

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.

Except that you *cant* do the following :
is superfluous. Just go:

Local Temp:ExtendClass = ExtendClass( BaseClass.Create ())


Temp will be null.
Why? Because you can't cast in that direction.

What the line above is basically saying is "give me an ExtendClass from a BaseClass and somehow magically create the extra memory that the ExtendClass will need for all its fields etc." - which Max doesn't do.

You can cast in the *opposite* direction, eg :

Local	Temp:BaseClass	= BaseClass( ExtendClass.Create ())

because an ExtendClass is already a BaseClass.

In the above code where "FOne = 1", and if you always intend setting the value to this when the object is created, why not have :
Field FOne:Int = 1

Or, you want another method to hold initialisation stuff, you can make a "New()" method like so :
Type BaseClass

	Field FOne:Int

	Method New()
		FOne = 1
	End Method

EndType

Since New() is called *for you* whenever an object is created, it's very useful.

Here's a small example to show you how you can set fields in different places in the code.
SuperStrict

Type baseclass

	Field FOne:Int = 99
	Field FNothing:Int

	Function create:baseclass()
		Local this:baseclass = New baseclass
		
		this.FNothing = 100 ' unless we call create explicitly, this never happens
		
		Return this
	End Function
	
	Method New()
		FOne = 1  ' the field changes when the object is initialized
	End Method
	
End Type

Type extendclass Extends baseclass

	Field FTwo:Int
	Field FThree:Int

	Function create:extendclass()
		Local this:extendclass = New extendclass
		
		this.FTwo = 2
		
		Return this
	End Function
	
	Method New()
		FThree = 3 ' the field changes when the object is initialized
	End Method
	
End Type

' a small test :
Local x:extendclass = extendClass.Create()

Print x.FNothing
Print x.FOne
Print x.FTwo
Print x.FThree

Notice how the New() of the baseclass is called, even when you are creating the extendclass object. This is because max needs to internally create all parent parts of a type when you create a subtype.
You can also see this when you are debugging. If you look at a variable that is a subtype of another type you will see the details split into sections. A bit for each type that the object represents.

Once you get the hang of OO with Max, it's really very cool :-)

Hope this helps a bit.