x=New x error

BlitzMax Forums/BlitzMax Programming/x=New x error

Curtastic(Posted 2005) [#1]
I know this is not supposed to work, but sometimes I get a windows error message when I do this on accident
is there some OOP thing that is why this compiles?
strict
Type tbat
Field x
EndType

Local i:int
Local bat:tbat

Print "hi"

'bat=New i 'does not compile. ok
bat=New bat 'compiles. why?



Michael Reitzenstein(Posted 2005) [#2]
I think bat being null when you do it is the problem. New, when passed an object instead of a type name, will create a new object of the same type as that object, but if that object is null it shouldn't work.


Curtastic(Posted 2005) [#3]
ok thanks, thats really wierd.

[this works]
Type person
	Field name:String
EndType

Local bob:person
Local joe:person

joe=New person

bob=New joe



BOB EQUALS NEW JOE. (works only if joe happens to be not null at the time, even though joe is always declared as a person)


Michael Reitzenstein(Posted 2005) [#4]
What's weird about that?


Dreamora(Posted 2005) [#5]
on the first sample

new only accepts types. it does the same as "new" in c like languages: it creates a new instance of the class / type you tell it.
There is no type "i" ( as well as "int" etc are no types that can be instanced )

and the second sample:

new requires, as mentioned above, the TYPE, not a variable ( see the helpfiles on userdefined types for further informations )


Warren(Posted 2005) [#6]
On the "bob=New joe" sample, the compiler should be puking because "joe" isn't a type. Looks like a compiler bug...


Curtastic(Posted 2005) [#7]

and the second sample:

new requires, as mentioned above, the TYPE, not a variable ( see the helpfiles on userdefined types for further informations )


my code works on the second example.


AaronK(Posted 2005) [#8]
Damn, I wrote a test program and was thinking, hmm, maybe Mark made that a way to do copy construction, but no. How about that Mark?

Aaron


Curtastic(Posted 2005) [#9]
heh ya, that would explain why it works only when joe is not null, (in bob:person=new joe)
But it should be fixed that it gives a windows program crash (in a similar situation) with debug ON. that shouldnt ever happen with debug on.


Michael Reitzenstein(Posted 2005) [#10]
As I said,

New, when passed an object instead of a type name, will create a new object of the same type as that object


It's a documentation issue.


The feature is so you can do something like this - which *doesn't* work, because SizeOf is incorrectly returning 0:

Type CloneableObject
	
	Method Clone:Object( )
	
		Local sel:Object = Self
		Local obj:Object = New sel
				
		MemCopy( Byte Ptr( Varptr( obj ) ), Byte Ptr( Varptr( sel ) ), SizeOf( sel ) )

		Return obj
	
	End Method
	
End Type

Type Enemy Extends CloneableObject

	Field x#, y#

End Type

Local BadGuy:Enemy = New Enemy
BadGuy.x = 50
BadGuy.y = 60

Local AnotherBadGuy:Enemy = Enemy( BadGuy.Clone( ) )

RuntimeError AnotherBadGuy.x + "," + AnotherBadGuy.y