Constructor/Destructor identification

General FreeBASIC programming questions.
fxm
Moderator
Posts: 12082
Joined: Apr 22, 2009 12:46
Location: Paris suburbs, FRANCE

Re: Constructor/Destructor identification

Post by fxm »

Bad luck, extending OBJECT induces an implicit constructor.
But suppressing 'Extends Object' (no any constructor) does not change the code result.
dodicat
Posts: 7976
Joined: Jan 10, 2006 20:30
Location: Scotland

Re: Constructor/Destructor identification

Post by dodicat »

If extending object induces an implicit constructor (construction of the instances) then why are the values of .d not set to zero?
If I give a default
type udt extends object
as double d=8
declare destructor
end type
then the values of the .d fields are still not initialized in any way.
I can override the any at a later time of course, using the implicit constructor, whether extending object or not.

Code: Select all


type udt extends object
      as double d=8
      declare destructor
end type



destructor udt
print @this,d;tab(60);__function__
end destructor

Dim As udt instance1=any:print @instance1,instance1.d;tab(60);__function__
Dim As udt instance0=any:print @instance0,instance0.d;tab(60);__function__
Dim As udt instance3=any:print @instance3,instance3.d;tab(60);__function__
Dim As udt instance2=any:print @instance2,instance2.d;tab(60);__function__
instance1.constructor
instance0.constructor
instance3.constructor
instance2.constructor
print
print "done"



sub fin destructor
      print "press a key"
      sleep
end sub
 
fxm
Moderator
Posts: 12082
Joined: Apr 22, 2009 12:46
Location: Paris suburbs, FRANCE

Re: Constructor/Destructor identification

Post by fxm »

The 'Object' type has an implicit constructor (always called) to set to '0' the virtual pointer ('vptr') value (pointer found at '0' address of the instance).
Then, if the 'UDT' constructor is called, the 'vptr' value is set to the address of the virtual table ('vtbl') corresponding to the 'UDT' type (and the member data are initialized if needed).

Code: Select all

Type UDT Extends Object
    As Double d = 8
End Type

Dim As UDT instance = Any

Print Cptr(Any Ptr Ptr, @instance)[0]
Print instance.d
Print

instance.Constructor()

Print Cptr(Any Ptr Ptr, @instance)[0]
Print instance.d
Sleep

Warning: if only the 'Object' constructor is called, such an instance ('Dim As UDT instance = Any') is not recognized as an 'UDT' instance by the Run Time Type Identification (RTTI) process (no virtuality neither polymorphism available).
dodicat
Posts: 7976
Joined: Jan 10, 2006 20:30
Location: Scotland

Re: Constructor/Destructor identification

Post by dodicat »

That's fine.
Thanks.
Post Reply