Copy Constructors
A copy
constructor creates a new object by copying variables from an existing object of the same type. For example, you might want to pass a Time
object to a Time
constructor so that the new Time
object has the same values as the old one.
Visual Basic 2005 does not provide a copy constructor, so if you want one you must provide it yourself. Such a constructor copies the elements from the original object into the new one, as shown in Example 18-4.
Example 18-4. Copy constructor
Public Sub New(ByVal existingObject As Time) year = existingObject.year month = existingObject.month dayOfMonth = existingObject.dayOfMonth hour = existingObject.hour minute = existingObject.minute second = existingObject.second End Sub
A copy constructor is invoked by instantiating an object of type Time
and passing it the name of the Time
object to be copied:
Dim t2 As New Time(timeObject)
The Me Keyword
The keyword Me
refers to the current instance of an object. The Me
reference is a hidden reference to every non-Shared
method of a class (Shared
methods are discussed later). Each method can refer to the other methods and variables of that object by way of the Me
reference.
The Me
reference may be used to distinguish instance members that have the same name as parameters, as in the following:
Public Sub SomeMethod(ByVal hour As Integer) Me.hour = hour End Sub
In this example, SomeMethod
takes a parameter (hour
) with the same name as a member variable of the class. The Me
reference is used to resolve ...
Get Programming Visual Basic 2005 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.