Constructors

In Example 5-3, notice that the statement that creates the Time object looks as though it is invoking a method:

 Dim timeObject As New Time( )

In fact, a method is invoked whenever you instantiate an object. This method is called a constructor. Each time you define a class you are free to define your own constructor, but if you don’t, the compiler will provide one for you invisibly and automatically. The job of a constructor is to create the object specified by a class and to put it into a valid state. Before the constructor runs, the object is just a blob of memory; after the constructor completes, the memory holds a valid instance of the class.

The Time class of Example 5-3 does not define a constructor. As noted earlier, if you do not declare a constructor the compiler provides one for you. The constructor provided by the compiler creates the object but takes no other action.

Tip

Any constructor that takes no arguments is called a default constructor . It turns out that the constructor provided by the compiler takes no arguments, and hence is a default constructor. This terminology has caused a great deal of confusion. You can create your own default constructor, and if you do not create a constructor at all, the compiler will create a default constructor for you, by default.

If you do not explicitly initialize your member variables, they are initialized to default values (integers to 0, strings to the empty string, etc.). Table 5-2 lists the default values assigned ...

Get Programming Visual Basic .NET, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.