Constructor
 
Called automatically when a class or user defined type is created

Syntax

Type typename
Declare Constructor ( )
Declare Constructor ( [ ByRef | ByVal ] parameter As datatype [ = default ] [, ... ] )
End Type

Constructor typename ( [ parameters ] )
statements
End Constructor

Parameters

typename
name of the Type of Class

Description

Constructor methods are called when a user defined Type or Class variable is created.

typename 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 or class. The exact constructor method called depends on the parameter signature matched when the variable is initialized. More than one parameter may exist in a constructor method declaration.

A constructor method is passed a hidden This parameter having the same type as typename. This is optionally used to access the fields of the Type or Class which is to be initialized in the Constructor method.

Chaining of constructors in nested types is supported. Any fields that have their own default constructor are called first.

Constructors are called when declaring global or local static instances of typename and when allocating typename dynamically using the New operator.

Example

Simple constructor example for beginners.
Type MyObj
  Foo As Integer Ptr
  
    '' Constructor to create our integer, and set its value.
  Declare Constructor( ByVal DefVal As Integer = 0 )
    '' Destroy our integer on object deletion.
  Declare Destructor()
End Type

Constructor MyObj( ByVal DefVal As Integer = 0 )
  Print "Creating a new integer in MyObj!"
  Print "The Integer will have the value of: " & DefVal
  Print ""
  
    '' Create a pointer, and set its value to the one passed to the
    '' Constructor.
  This.Foo = New Integer
  *This.Foo = DefVal
End Constructor

Destructor MyObj()
  Print "Deleting our Integer in MyObj!"
  Print ""
  
    '' Delete the pointer we created in MyObj.
  Delete This.Foo
  This.Foo = 0
End Destructor


Scope
    '' Create 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.
  Print "The Value of our integer 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 String

  Declare Constructor ()
  Declare Constructor ( a As Integer )
  Declare Constructor ( a As Single  ) 
  Declare Constructor ( a As String, b As Byte ) 

  Declare Operator Cast () As String

End Type

Constructor sample ()
  Print "constructor sample ()"
  Print
  this._text = "Empty"
End Constructor

Constructor sample ( a As Integer )
  Print "constructor sample ( a as integer )"
  Print "  a = "; a
  Print
  this._text = Str(a)
End Constructor

Constructor sample ( a As Single )
  Print "constructor sample ( a as single )"
  Print "  a = "; a
  Print
  this._text = Str(a)
End Constructor

Constructor sample ( a As String, b As Byte )
  Print "constructor sample ( a as string, b as byte )"
  Print "  a = "; a
  Print "  b = "; b
  Print
  this._text = Str(a) + "," + Str(b)
End Constructor

Operator sample.cast () As String
  Return this._text
End Operator

Print "Creating x1"
Dim x1 As sample

Print "Creating x2"
Dim x2 As sample = 1

Print "Creating x3"
Dim x3 As sample = 99.9

Print "Creating x4"
Dim x4 As sample = sample( "aaa", 1 )

Print "Values:"
Print "  x1 = "; x1
Print "  x2 = "; x2
Print "  x3 = "; x3
Print "  x4 = "; x4

Dialect Differences

  • Object-related features are supported only in the -lang fb option

Differences from QB

  • New to FreeBASIC

See also

Знаете ли Вы, что такое "усталость света"?
Усталость света, анг. tired light - это явление потери энергии квантом электромагнитного излучения при прохождении космических расстояний, то же самое, что эффект красного смещения спектра далеких галактик, обнаруженный Эдвином Хабблом в 1926 г.
На самом деле кванты света, проходя миллиарды световых лет, отдают свою энергию эфиру, "пустому пространству", так как он является реальной физической средой - носителем электромагнитных колебаний с ненулевой вязкостью или трением, и, следовательно, колебания в этой среде должны затухать с расходом энергии на трение. Трение это чрезвычайно мало, а потому эффект "старения света" или "красное смещение Хаббла" обнаруживается лишь на межгалактических расстояниях.
Таким образом, свет далеких звезд не суммируется со светом ближних. Далекие звезды становятся красными, а совсем далекие уходят в радиодиапазон и перестают быть видимыми вообще. Это реально наблюдаемое явление астрономии глубокого космоса. Подробнее читайте в FAQ по эфирной физике.

НОВОСТИ ФОРУМА

Форум Рыцари теории эфира


Рыцари теории эфира
 10.11.2021 - 12:37: ПЕРСОНАЛИИ - Personalias -> WHO IS WHO - КТО ЕСТЬ КТО - Карим_Хайдаров.
10.11.2021 - 12:36: СОВЕСТЬ - Conscience -> РАСЧЕЛОВЕЧИВАНИЕ ЧЕЛОВЕКА. КОМУ ЭТО НАДО? - Карим_Хайдаров.
10.11.2021 - 12:36: ВОСПИТАНИЕ, ПРОСВЕЩЕНИЕ, ОБРАЗОВАНИЕ - Upbringing, Inlightening, Education -> Просвещение от д.м.н. Александра Алексеевича Редько - Карим_Хайдаров.
10.11.2021 - 12:35: ЭКОЛОГИЯ - Ecology -> Биологическая безопасность населения - Карим_Хайдаров.
10.11.2021 - 12:34: ВОЙНА, ПОЛИТИКА И НАУКА - War, Politics and Science -> Проблема государственного терроризма - Карим_Хайдаров.
10.11.2021 - 12:34: ВОЙНА, ПОЛИТИКА И НАУКА - War, Politics and Science -> ПРАВОСУДИЯ.НЕТ - Карим_Хайдаров.
10.11.2021 - 12:34: ВОСПИТАНИЕ, ПРОСВЕЩЕНИЕ, ОБРАЗОВАНИЕ - Upbringing, Inlightening, Education -> Просвещение от Вадима Глогера, США - Карим_Хайдаров.
10.11.2021 - 09:18: НОВЫЕ ТЕХНОЛОГИИ - New Technologies -> Волновая генетика Петра Гаряева, 5G-контроль и управление - Карим_Хайдаров.
10.11.2021 - 09:18: ЭКОЛОГИЯ - Ecology -> ЭКОЛОГИЯ ДЛЯ ВСЕХ - Карим_Хайдаров.
10.11.2021 - 09:16: ЭКОЛОГИЯ - Ecology -> ПРОБЛЕМЫ МЕДИЦИНЫ - Карим_Хайдаров.
10.11.2021 - 09:15: ВОСПИТАНИЕ, ПРОСВЕЩЕНИЕ, ОБРАЗОВАНИЕ - Upbringing, Inlightening, Education -> Просвещение от Екатерины Коваленко - Карим_Хайдаров.
10.11.2021 - 09:13: ВОСПИТАНИЕ, ПРОСВЕЩЕНИЕ, ОБРАЗОВАНИЕ - Upbringing, Inlightening, Education -> Просвещение от Вильгельма Варкентина - Карим_Хайдаров.
Bourabai Research - Технологии XXI века Bourabai Research Institution