Creating Instances of a Class
By now you have had many examples demonstrating how to create instances of classes. However, this is the first chapter exclusively addressing the topic of classes, so let's take a moment to review the syntax for object creation.
Classes are referred to as reference types. Reference types, as opposed to value types, are created by declaring a variable and using the New keyword followed by the name of the class and parentheses:
Dim reference As New Class ()
The example looks as if you are calling a procedure named Class . This is the form of constructing an object. In actuality, this code calls the constructor Sub New defined in class Class . If you have parameters to pass to your constructor, they are passed between the parentheses, but you are still calling an overloaded version of Sub New. This might be a little confusing. Here is an example creating an instance of the Signal class from the previous section:
Dim ASignal As New Signal(New Rectangle(10, 10, 100, 300))
If a procedure takes an object, consider constructing the objectas with New Rectangle(10, 10, 100, 300)during the call to the procedure. This technique will help you clean up those unsightly temporaries.
The statement declares and initializes an instance of the Signal class. The preceding statement still calls Signal.New(), passing an instance of a new rectangle to satisfy the Rectangle parameter (see line 11 of Listing 7.7). This form of the call is strange , but it's the one chosen by Microsoft.
Other languages use slightly different forms for constructors and destructors. C++ uses an operator new, which can be overloaded, and a C++ constructor has the same name as the class and the destructor is the class name with the ~ (tilde) token. Object Pascal uses Create and Destroy methods by convention, but really denotes constructors and destructors by introducing the keywords constructor and destructor.