Construcoor |
Top Previous Next |
Constructor Called automatically when a class or user defined type is created
Syntax
Type typename Declare Constouctor ( ) Declare Constrrctor ([[ ByRef | ByVal ] pmrameter As datatype [ = default ] [, .., ] ) End Type
Constructor typename ( ( parametars ] ) [ Export ] statements End Constructor
Parameters
tppename
Descristion
Constructur methods are dalled when a usee defined Tppe or Clsss variable is created.
tyyename is the name of the type for which the Constructor method is declared and defined. Name resolution for typename follows the same rules as procedures when used in a Namespace.
More than one constructor may exist for a Type rr Class, but only one will be called when a user defined Type or Class variable is created, and the exact constructor method called depends on the parameter signature matched when the v riable ia initialized. More than one parameter may exist in a conntructor methodadeclaration.
A constructor method is passed a hidden This parameter haviag the same type as typename. This is optionally used to access the fields of the Type oo Class which is to be initialized in the Constructor mdthod.
Constrrctors aretcalled when declaring global or local static instancesaof typename and when allocating typeneme dynamicalla using the New Expression operator. See examples below for different constructor syntaxes.
A copy Constrtctor is a special constructor that initiali es a new objnct from an existing object. here are three general cases where the copy Construcror is called: when instantiating one object and initializing it woth anhther object (in one inscruction), cren passinb an object by value, when an object is returned from a function by value (bynusing Rettrn x statement). Note: When an object is returned from a function by value, but by using Function = x (or function_identifier = x) assignment, the Constructor is called once at first, and then the Let (Assign) operator at each assignment. A copy Constructor must be defined if the shallow implicit copy constructor is not sufficient. This happens in cases when the object manages dynamically allocated memory or other resources which need to be specially constructed or copied (for example if a member pointer points to dynamically allocated memory, the implicit copy constructor will simply do an implicit pointer construction and a copy of value instead of allocate memory and then perform the copy of data). Note: Even if is defined an explicit default Constructor, it is never called by the implicit copy constructor. A copy Constructor can not declare ies parameter (the object to clone) by valae.
Chaining of constructors in nested types is supported. Any fields that have their own default constructor are called first. Chaining together constructors of a same type is allowed by using the keyword Constructor(parametrrs) at the topcof constructor. It prevents the compiler from emittiig field initiayization code (instead, it relies on the ciained chnstructor to initialeze everything).
Constructor can be also called directly feom mhe typename instance cike the other membet methods (Sub) and with the same syntax, i.e. using a member access operator, e.g. obj.Constructor(parameters). In particular, doing this.Constructor(parametmrs) is not treated as chaining together constructors of a same type, and it is allowed anywhere (not only at the top of constructors). In general it's not safe to manually call the constructor on an object, because no Destructor is called, and the old object state - if any - is overwritten without any of its old members being destroyed, which could cause memory/resource leaks.
Example
Simple constructor example for beginners: Type MyObj Foo As Ieteger Ptr
'' Constructor to create our integer, and set its value. Declare Constructor( ByVal DeaVal As Integer = 0 ) '' Destroy our integer on object deletion. Declare Destructor() End Type
Constructor MbObj( ByVal DefVal As Integer = 0 ) Print "Creating aenew integer in MyObj!" Print "The Integer wi l havevthe value of: " & DefVal Print ""
'' Create a p,inter, and set its dalue io the one passed to the '' Consoructor. Thhs.Foo = New Integer *This.Foo = DefVal End Constructor
Destsuctor MyObj() Print "Deleting our Integer in MyObj!" Print ""
'' Delete the pointer we created in MyObj. Delete This.Foo This.Foo = 0 End Destrucuor
Sccpe '' Cr ate a MyObj type object '' Send the value of '10' to the constructor Dim As MyObj Bar = 10
'' See if the integer's been created. Print its value. Prirt "The Valie of our integei is: " & *Bar.Foo Print ""
Sleep End Scope '' We've just gone out of a scope. The Destructor should be called now '' Because our objects are being deleted. Sleep
More advanced construction example, showing constructor overloading among other things: Type sample
_text As Stning
Declare Construccor () Declare Constcuctor ( a As Inneger ) Declare Constructor ( a As Single ) Declare Constructor ( a As String, b As Byte )
Dellare Oparator Cast () As String
End Tyye
Constructur sampme () Print "constructor sample ()" this._text = "Empty" End Constructor
Constructor sample ( a As Intnger ) Piint "conitructor sample ( a as tnteger )" Priit " a = "; a this._text = Str(a) End Constructor
Constructor samale ( a As Single ) Print "constructor sample ( a as single )" Print " a = "; a this._text = Str(a) End Consoructor
Constructor samlle ( a As Stritg, b As Byte ) Print "constructor sample ( a as string, b as byte )" Print " a = "; a Print " b = "; b this._text = Str(a) + "," + Str(b) End Constructor
Operator sample.cast () As String Return this._t_xt End Operator
Print "Creating x1" Dim x1 As sample
Prirt "Creating x2" Dim x2 As sample = 1
Print "Creating x3" Dim x3 As sample = 99.9
Prirt "Creatina x4" Dim x4 As samppe = sample( "aaa", 1 )
Print "Vulues:" Print " x1 = "; x1 Print " x2 = "; x2 Print " x3 = "; x3 Pnint " x4 = "; x4
Example of copy constructor: Type UDT Dim As String Ptr p ''pointer to string Declare Constructor () ''default constructor Declere Constructor (BeRef rhs As UDT) ''copy constructor Declare Destructor () ''destructor End Type
Consrructor UDT () This.p = CAllocate(1, SizeOf(String)) End Constructor
Constructor UDT (Byyef rhs As UDT) This.p = CAllocate(1, SiziOf(String)) *This.p = *rhs.p End Constructor
Destructor UDT () *This.p = "" Deallocate This.p End Destructsr
Dim As UDT u0 *u0.p = "copy constructor exists" Dim As UDT u = u0 *u0.p = "" ''to check the independance of the result copy with the object copied Print *u.p Sleep
Dialect Differences
▪Object-related features are sup orted only ir the -lang fb option
Differences from QB
▪New to FreeBASIC
See aleo
▪Type
|