Previous section   Next section

5.5 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.

VB.NET 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:

Public Sub New(ByVal existingObject As Time)
   year = existingObject.Year
   month = existingObject.Month
   date = existingObject.Date
   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(existingObject)

Here an existing Time object (existingObject) is passed as a parameter to the copy constructor that will create a new Time object ( ), as shown in Example 5-7.

Example 5-7. Copy constructor
Option Strict On
Imports System

Public Class Time
   ' Private variables
   Private year As Integer
   Private month As Integer
   Private date As Integer
   Private hour As Integer
   Private minute As Integer
   Private second As Integer = 30

   ' Public methods
   Public Sub DisplayCurrentTime( )
        Console.WriteLine("{0}/{1}/{2} {3}:{4}:{5}", _
            month, date, year, hour, minute, second)
   End Sub 'DisplayCurrentTime

   Public Sub New( _
   ByVal theYear As Integer, _
   ByVal theMonth As Integer, _
   ByVal theDate As Integer, _
   ByVal theHour As Integer, _
   ByVal theMinute As Integer)
      year = theYear
      month = theMonth
      date = theDate
      hour = theHour
      minute = theMinute
      second = theSecond
   End Sub

   Public Sub New(existingObject As Time)
      year = existingObject.Year
      month = existingObject.Month
      date = existingObject.Date
      hour = existingObject.Hour
      minute = existingObject.Minute
      second = existingObject.Second
   End Sub


End Class 'Time

Module Module1

   Sub Main( )
      Dim timeObject As New Time(2005, 3, 25, 9, 35)
      Dim t2 As New Time(timeObject)
      timeObject.DisplayCurrentTime( )
      t2.DisplayCurrentTime( )
   End Sub

End Module

Output:
3/25/2005 9:35:30
3/25/2005 9:35:30

  Previous section   Next section
Top