IT SOLUTIONS
Your full service technology partner! 
-Collapse +Expand
To/From Code
   ► KBTo/From GuidesReferenceOOP Details  Print This     

Constructor (Cross Ref > OOP Details)

Constructor

General Info: Class Constructor

Constructors are called when you instantiate an object from a class. This is where you can initialize variables and put code you wish executed each time the class is created. When you initially set the member fields and properties of an object, you are initializing the state of the object. The state of an object is the values of all it's member fields and properties at a given time.

Languages Focus

What is the syntax? Can you overload constructors? Is a special method name reserved for constructors?

Access VBA:  "Constructors" Class_Initialize

When an object instance is created from a class, Access VBA calls a special parameter-less sub named Class_Initialize. Since you cannot specify parameters for this sub, you also cannot overload it.

When a class is destroyed, Access VBA calls a special sub called Class_Terminate.

More Info / Comment

Linked Certification Question(s)

The following are practice certification questions with answers highlighted. These questions were prepared by Mike Prestwood and are intended to stress an important aspect of this KB post. All our practice questions are intended to prepare you generally for passing any certification test as well as prepare you for professional work.

Advanced

1 Advanced Level Question

Question #1: Multiple Choice

In Access object oriented programming, when an object instance is created from a class, Access VBA calls a special parameter-less sub named what?

Answer:
1. 

Class_New

2. 

New

3. 

Initialize

4. 

Class_Initialize

5. 

Class_Create

More Info

Definition:  Class Constructor
 

ASP Classic:  "Constructors" Class_Initialize

When an object instance is created from a class, ASP calls a special parameter-less sub named Class_Initialize. Since you cannot specify parameters for this sub, you also cannot overload it.

When a class is destroyed, ASP calls a special sub called Class_Terminate.

Syntax Example:
Class Cyborg
  Public CyborgName
 
 Public Sub Class_Initialize
   Response.Write "<br>Class created"
   CyborgName = "Cameron"
  End Sub 
End Class

Working Example

The following working example contains both a constructor and destructor, ASP's Class_Initialize and Class_Terminate subs. In this example, we are implicitly destroying the object (letting IIS destroy the object when the variable goes out of scope).

You can explicitly destroy an object by using Set MyRobot = Nothing. In ASP Classic, it is recommended that you explicitly destroy all objects.

<%@LANGUAGE=VBScript%>
<%Option Explicit%>
<html>
<body>
  
<%
Dim MyRobot
Set MyRobot = new Cyborg
Response.Write "<br>My robot's name is " & MyRobot.CyborgName & "."
  
//Object destroyed implicitly here
//and Class_Terminate is called.
%>
  
</body>
</html>
  
<%
Class Cyborg
 Public CyborgName
 
 Public Sub Class_Initialize
  Response.Write "<br>Class created"
  CyborgName = "Cameron"
 End Sub
 
  
 Public Sub Class_Terminate
  Response.Write "<br>Class destroyed"
 End Sub 
End Class

%> 


Linked Certification Question(s)

The following are practice certification questions with answers highlighted. These questions were prepared by Mike Prestwood and are intended to stress an important aspect of this KB post. All our practice questions are intended to prepare you generally for passing any certification test as well as prepare you for professional work.

Advanced

1 Advanced Level Question

Question #1: Multiple Choice

In ASP Classic object oriented programming, when an object instance is created from a class, ASP calls a special parameter-less sub named what?

Answer:
1. 

Class_Initialize

2. 

Class_New

3. 

New

4. 

Initialize

5. 

Class_Create

More Info

Code:  ASP Classic Constructors (Class_Initialize)
Definition:  Class Constructor

C#:  "Constructors" Use class name

In C#, a constructor is called whenever a class or struct is created. A constructor is a method with the same name as the class with no return value and you can overload the constructor.

If you do not create a constructor, C# will create an implicit constructor that initializes all member fields to their default values.

Constructors can execute at two different times. Static constructors are executed by the CLR before any objects are instantiated. Regular constructors are executed when you create an object.

Syntax Example:
public class Cyborg
{
public string CyborgName;
  
  //Constructor.
  public Cyborg(string pName)
{
CyborgName = pName;
}
}

C# Constructor Details

  • Use class name. A method with the same name as the class.
  • No return value.
  • Overloadable. You can overload your constructors.
  • Optional. When you create classes, you do not have to create a class constructor. If you do not, the constructor for the parent class is called.
  • Static Constructors. You can make a constructor static (class member fields are initialized by the CLR prior to any object instantiations).

Overloading C# Constructors

You can overload a constructor with various parameters that initialize object instances to various states.

public class Cyborg
  {
    public string CyborgName;
  
    //Constructor with no params.
    public Cyborg() { }
  
    //Constructor with a parameter.
    public Cyborg(string pName)
    {
      CyborgName = pName;
    }
  }

Working WinForms Example

The following demonstrates using a finalizer and System.GC.Collect(). I placed a MessageBox.Show() in the finalizer so you can see when it is called. The finalizer gets called when the compiler needs to free resources or you call System.GC.Collect(). You'll notice that although the local variable in the button click event falls out of scope, your finalizer is not called until either you close the form or click the button that calls System.GC.Collect().

Create a form with two buttons and add code as follows:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace CR_Constructor
{
  public partial class Form1 : Form
  {
    public Form1()
    {
      InitializeComponent();
    }
    private void button1_Click(object sender, EventArgs e)
    {
      //Use class calling no parameter constructor.
      Cyborg MyRobot1 = new Cyborg();
      MyRobot1.CyborgName = "John";
      MessageBox.Show("My robot's name is " + MyRobot1.CyborgName);
  
      //Use the class calling an overloaded 
      //constructor with a single parameter.
      Cyborg MyRobot2 = new Cyborg("Cameron");
      MessageBox.Show("My robot's name is " + MyRobot2.CyborgName);
    }
  }
  
  public class Cyborg
  {
    public string CyborgName;
  
    //Constructor with no params.
    public Cyborg() { }
  
    //Constructor with a parameter.
    public Cyborg(string pName)
    {
      CyborgName = pName;
    }
  }

Static Constructors

You can make a constructor static. With a static constructor, the CLR initializes the static class member fields prior to any object instantiations. You can have only one static constructor with no parameters.

public class Cyborg
{
  //Executes once per program.
  static Cyborg() { }
}

You can have a static constructor and a regular constructor. The static constructor executes once prior to any object instantiations then the regular constructor executes every time you instantiate an object. At first glance of the following code, you might think it will not compile because it breaks the rules of overloading. However, it doesn't break any rules because each method is called at a different time.

public class Cyborg
{
  public string CyborgName;
  
  //Executes once per program. Notice no access modifier.
  static Cyborg() { }
  //Executes once per object instantiation.
  public Cyborg() { }
}


Linked Certification Question(s)

The following are practice certification questions with answers highlighted. These questions were prepared by Mike Prestwood and are intended to stress an important aspect of this KB post. All our practice questions are intended to prepare you generally for passing any certification test as well as prepare you for professional work.

Beginner

1 Beginner Level Question

Question #1: True or False?

If you do not create a developer defined constructor, C# creates an implicit constructor and initializes all member fields to their default values.

Answer:
  • True
  • False
  • Intermediate

    1 Intermediate Level Question

    Question #2: Multiple Choice

    The method name of a constructor is?

    Answer:
    1. 

    A method named New.

    2. 

    An unnamed method that uses the constructor keyword.

    3. 

    A method with the same name as the class and with no return value.

    4. 

    Any method name that uses the constructor keyword.

    Advanced

    1 Advanced Level Question

    Question #3: True or False?

    You can overload static constructors.

    Answer:
  • True
  • False
  • More Info

    Code:  C# Constructors (Use class name)
    Code:  C# Finalizer (~ClassName)
    Definition:  Class Constructor

    C++:  "Constructors" Use Class name

    A member function with the same name as the class.

    Syntax Example:
    class X {
    public:
    X(); // constructor for class X
    };


    Linked Certification Question(s)

    The following are practice certification questions with answers highlighted. These questions were prepared by Mike Prestwood and are intended to stress an important aspect of this KB post. All our practice questions are intended to prepare you generally for passing any certification test as well as prepare you for professional work.

    Beginner

    1 Beginner Level Question

    Question #1: Multiple Choice

    In C++, when you create an object instance from a class, C++ calls a special member function named what?

    Answer:
    1. 

    Same name as the class.

    2. 

    New

    3. 

    Class_Initialize

    4. 

    ~ + class name, i.e. ~Person

    5. 

    Create

    More Info

    Definition:  Class Constructor
     

    Corel Paradox:  "Constructors" Not Supported

    Delphi:  "Constructors" constructor

    In Delphi, use the constructor keyword to signify which method or methods are constructors for a class. It is traditional but not required to use a procedure called Create.

    In addition to having multiple named constructors, you can overload constructors.

    Syntax Example:
    //Interface section.
    TCyborg = class(TObject)
    public
      constructor Create;
    end; 

    Then implement the class constructor in the Implementation section.

    constructor TCyborg.Create;
    begin
      inherited;  //Call the parent Create method
    end;

    Step by Step Example

    The following is a step-by-step tutorial on creating your first Delphi class and does include an inheritance example. From this simple tutorial, you can then experiment with the various class inheritance features.

    Constructor and Destructor Example

    SystemTime Class: In this final example, we want to create a class that will allow us to store the current time and then to restore it when we are finished with it.

    Source Code for our class

    unit SystemTime;  
    interface
    uses
       Windows, Messages, SysUtils, Classes, Graphics,
       Controls, Forms, Dialogs, StdCtrls;  
    type
       TSysTime = class(TObject)
       private
         FStartDateTime : TDateTime;
       protected
       { Protected declarations }
       public
         constructor Create; virtual;
         destructor Destroy; override;
          procedure SetOldTime;
       published
       { Published declarations }
    end;
    implementation
    constructor TSysTime.Create; 
    begin
       FStartDateTime := Now;
    end;
    destructor TSysTime.Destroy;
    var
       NewTime : TSystemTime;
    begin
       DateTimeToSystemTime(FStartDateTime, NewTime);
       SetSystemTime(NewTime); 
    end;  
    procedure TSysTime.SetOldTime; 
    var
       NewTime : TSystemTime;  
    begin
       // set time to an arbitrary date/time
       NewTime.wYear := 1996;
       NewTime.wMonth := 1; 
       NewTime.wDayOfWeek    := 1;
       NewTime.wDay := 8;
       NewTime.wHour := 5;
       NewTime.wMinute  := 32;
       NewTime.wSecond  := 22;
       NewTime.wMilliseconds := 10;
       SetSystemTime(NewTime);
     end;
    end.


    Linked Certification Question(s)

    The following are practice certification questions with answers highlighted. These questions were prepared by Mike Prestwood and are intended to stress an important aspect of this KB post. All our practice questions are intended to prepare you generally for passing any certification test as well as prepare you for professional work.

    Intermediate

    2 Intermediate Level Questions

    Question #1: Multiple Choice

    The method name of a constructor is?

    Answer:
    1. 

    Create

    2. 

    Not defined, use the constructor keyword to signify which method or methods are constructors for a class.

    3. 

    New

    4. 

    Same name as the class.

    5. 

    ~ + class name, i.e. ~Person

    Question #2: True or False?

    The method name for a class constructor can be anything including Create and CreateFromTable.

    Answer:
  • True
  • False
  • More Info

    Definition:  Class Constructor
    Code:  Delphi Constructors (constructor)

    Delphi Prism:  "Constructors" constructor + class name

    In Prism, a constructor is called whenever a class or struct is created. You use the constructor keyword with an unnamed method. You can overload the constructor simply by adding two or more unnamed methods with various parameters.

    Prism also supports a Create constructor method for backward compatibility with Delphi for Win32.

    If you do not create a constructor, Prism will create an implicit constructor that initializes all member fields to their default values.

    Constructors can execute at two different times. Static constructors are executed by the CLR before any objects are instantiated. Regular constructors are executed when you create an object.

    Syntax Example:
    Cyborg = public class
    public
      constructor();
      constructor(pName: String);
    end;

    Working WinForms Example

    The following example demonstrates overloading a constructor so that you have the option to initialize a property at creation.

    Create a form and place a button on it and alter the code as follows:

    namespace CR_Constructor;
      
    interface
      
    uses
      System.Drawing,
      System.Collections,
      System.Collections.Generic,
      System.Linq,
      System.Windows.Forms,
      System.ComponentModel;
      
    type
      /// <summary>
      /// Summary description for MainForm.
      /// </summary>
      MainForm = partial class(System.Windows.Forms.Form)
      private
        method button1_Click(sender: System.Object; e: System.EventArgs);
      protected
        method Dispose(disposing: Boolean); override;
      public
        constructor;
      end;
      
      Cyborg = class(System.Object)
      private
      public
        property CyborgName: String;  //Property using implicit syntax.
        constructor();                //No parems constructor.
        constructor(pName: String); //Constructor with a string parameter.
      end;
      
    implementation
    {$REGION Construction and Disposition}
    constructor MainForm;
    begin
      //
      // Required for Windows Form Designer support
      //
      InitializeComponent();
      //
      // TODO: Add any constructor code after InitializeComponent call
      //
    end;
      
    method MainForm.Dispose(disposing: Boolean);
    begin
      if disposing then begin
        if assigned(components) then
          components.Dispose();
        //
        // TODO: Add custom disposition code here
        //
      end;
      inherited Dispose(disposing);
    end;
    {$ENDREGION}
      
    method MainForm.button1_Click(sender: System.Object; e: System.EventArgs);
    var
      MyRobot1: Cyborg;
      MyRobot2: Cyborg;
    begin
      MyRobot1 := New Cyborg;
      MyRobot1.CyborgName := "John";
      MessageBox.Show("My robot's name is " + MyRobot1.CyborgName + ".");
      
      MyRobot2 := New Cyborg("Cameron");
      MessageBox.Show("My robot's name is " + MyRobot2.CyborgName + ".");
    end;
      
    //Constructor with no parems.
    constructor Cyborg();
    begin
    end;
      
    //Constructor with a string parameter.
    constructor Cyborg(pName: String);
    begin
      CyborgName := pName;
    end;
    end.

    Use the Legacy Create Constructor

    If you turn on legacy support for Create, you can use the Delphi-style Create to instantiate objects instead of New:

    var
    MyRobot1: Cyborg;
    begin
    MyRobot1 := Cyborg.Create;
    T1.CyborgName := "John";
      //...
    end;

    To turn on legacy support for Create, in the solution explorer right click on your solution or project and select Properties. On the Compatibility tab, check Allow 'Create' Constructor calls.

    Allow Create constructor calls.



    Linked Certification Question(s)

    The following are practice certification questions with answers highlighted. These questions were prepared by Mike Prestwood and are intended to stress an important aspect of this KB post. All our practice questions are intended to prepare you generally for passing any certification test as well as prepare you for professional work.

    Intermediate

    1 Intermediate Level Question

    Question #1: True or False?

    The method name for a class constructor can be anything including Create and CreateFromTable.

    Answer:
  • True
  • False
  • More Info

    Definition:  Class Constructor
    Code:  Delphi Prism Constructors (constructor + class name)
    Code:  Delphi Prism Finalizer (finalize())

    Java:  "Constructors" Use class name

    A method with the same name as the class.

    Syntax Example:
    public class Cyborg{
      //Constructors have the same name as the class.
      public Cyborg() {
      }
    }


    Linked Certification Question(s)

    The following are practice certification questions with answers highlighted. These questions were prepared by Mike Prestwood and are intended to stress an important aspect of this KB post. All our practice questions are intended to prepare you generally for passing any certification test as well as prepare you for professional work.

    Beginner

    1 Beginner Level Question

    Question #1: Multiple Choice

    In C++, when you create an object instance from a class, C++ calls a special member function named what?

    Answer:
    1. 

    New

    2. 

    Class_Initialize

    3. 

    Same name as the class.

    4. 

    ~ + class name, i.e. ~Person

    5. 

    Create

    More Info

    Definition:  Class Constructor
     

    VB Classic:  "Constructors" Class_Initialize

    When an object instance is created from a class, VB6 calls a special parameter-less sub named Class_Initialize. Since you cannot specify parameters for this sub, you also cannot overload it.

    When a class is destroyed, VB6 calls a special sub called Class_Terminate.

    More Info / Comment

    Linked Certification Question(s)

    The following are practice certification questions with answers highlighted. These questions were prepared by Mike Prestwood and are intended to stress an important aspect of this KB post. All our practice questions are intended to prepare you generally for passing any certification test as well as prepare you for professional work.

    Advanced

    1 Advanced Level Question

    Question #1: Multiple Choice

    In VB Classic object oriented programming, when an object instance is created from a class, VB calls a special parameter-less sub named what?

    Answer:
    1. 

    New

    2. 

    Class_Initialize

    3. 

    Class_New

    4. 

    Initialize

    5. 

    A method with the same name as the class.

    More Info

    Definition:  Class Constructor
     

    VB.Net:  "Constructors" New

    In VB.Net, a constructor is called whenever a class or struct is created. A constructor is a sub named New. You can overload the constructor simply by adding two or more New subs with various parameters (overloaded constructors).

    If you do not create a constructor, VB.Net will create an implicit constructor that initializes all member fields to their default values.

    Constructors can execute at two different times. Static constructors are executed by the CLR before any objects are instantiated. Regular constructors are executed when you create an object.

    You can invoke the parent constructor with MyBase.New.

    Syntax Example:
    Public Class Cyborg
    Public CyborgName As String
      
      Public Sub New(ByVal pName As String)
    CyborgName = pName
    End Sub
    End Class

    Working WinForms Example

    The following example demonstrates using a constructor to initialize a public member field.

    Create a form and place a button on it and alter the code as follows:

    Public Class Form1
      Private Sub Button1_Click(ByVal sender As System.Object, _
          ByVal e As System.EventArgs) Handles Button1.Click
        Dim MyRobot As New Cyborg("Cameron")
      
        MessageBox.Show("My robot's name is " & MyRobot.CyborgName & ".")
    End Sub
    End Class
      
    Public Class Cyborg
    Public CyborgName As String
      
      Public Sub New(ByVal pName As String)
    CyborgName = pName
    End Sub
    End Class

    Overloading Constructors

    Here is a working example of overloading a constructor. In this example, we overload our New() constructor so you can either pass in a name or set the name after creation.

     
    Public Class Form1
      Private Sub Button1_Click(ByVal sender As System.Object, _
    ByVal e As System.EventArgs) Handles Button1.Click
     
        Dim MyRobot1 As New Cyborg()
    MyRobot1.CyborgName = "John"
    MessageBox.Show("My robot's name is " & MyRobot1.CyborgName & ".")
     
        Dim MyRobot2 As New Cyborg("Cameron")
    MessageBox.Show("My robot's name is " & MyRobot2.CyborgName & ".")
      End Sub
    End Class
     
    Public Class Cyborg
    Public CyborgName As String
     
      Public Sub New()
    End Sub
     
      Public Sub New(ByVal pName As String)
    CyborgName = pName
    End Sub

    End Class


    Linked Certification Question(s)

    The following are practice certification questions with answers highlighted. These questions were prepared by Mike Prestwood and are intended to stress an important aspect of this KB post. All our practice questions are intended to prepare you generally for passing any certification test as well as prepare you for professional work.

    Intermediate

    2 Intermediate Level Questions

    Question #1: Multiple Choice

    The method name of a constructor is?

    Answer:
    1. 

    Class_Initialize

    2. 

    ~ + class name, i.e. ~Person

    3. 

    New

    4. 

    Create

    5. 

    Same name as the class.

    Question #2: Yes or No?

    If you do not create a developer defined constructor, does VB.Net create an implicit constructor and initialize all member fields to their default values?

    Answer:
  • Yes
  • No
  • More Info

    Definition:  Class Constructor
    Code:  VB.Net Constructors (New)




    Go ahead!   Use Us! Call: 916-726-5675  Or visit our new sales site: 
    www.prestwood.com


    ©1995-2024 Prestwood IT Solutions.   [Security & Privacy]