Constructors






Constructors

In Figure, notice that the statement that creates the Time object looks as though it is invoking a Time( ) method:

     Time timeObject = new Time( );

In fact, a member 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 an instance of 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 Figure does not define a constructor, so the compiler implicitly provides one. The constructor provided by the compiler creates the object but takes no other action.

Any constructor that takes no arguments is called a default constructor. 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 innocuous values (integers to 0, strings to the empty string, etc.). Figure lists the default values assigned to various types.

Primitive types and their default values

Type

Default value

Numeric (int, long, etc.)

0

bool

False

char

'\0' (null)

enum

0

Reference

Null


Typically, you'll want to define your own constructor and provide it with arguments, so that the constructor can set the initial state for your object. In Figure, you want to pass in the current year, month, date, and so forth, so that the object is created with meaningful data.

You declare a constructor like any other member method, except:

  • The name of the constructor must be the same as the name of the class.

  • Constructors have no return type (not even void).

If there are arguments to be passed, you define an argument list just as you would for any other method. Figure declares a constructor for the Time class that accepts six arguments, one each for the year, month, date, hour, minute, and second for the new Time object you are creating.

Creating a constructor

using System;

public class Time
{
   // private member variables
   int year;
   int month;
   int date;
   int hour;
   int minute;
   int second;

   // public method
   public void DisplayCurrentTime( )
   {
      System.Console.WriteLine( "{0}/{1}/{2} {3}:{4}:{5}",
      month, date, year, hour, minute, second );
   }

   // constructor
   public Time( int theYear, int theMonth, int theDate,
   int theHour, int theMinute, int theSecond )
   {
      year = theYear;
      month = theMonth;
      date = theDate;
      hour = theHour;
      minute = theMinute;
      second = theSecond;
   }
}

public class Tester
{
   static void Main( )
   {
      Time timeObject = new Time( 2008, 8, 1, 9, 35, 20 );
      timeObject.DisplayCurrentTime( );
   }
}

The output looks like this:

    8/1/2008 9:35:20

In this example, the constructor takes a series of integer values and initializes all the member variables based on these parameters.

In this, as in virtually all the demonstration code, we've taken out all the error checking to simplify the presentation. Of course, this allows you to create a date such as July 45th 2005 at 29:32 a.m. Don't do that.


When the constructor finishes, the Time object exists and the values have been initialized. When DisplayCurrentTime( ) is called in Main( ), the values are displayed.

Try commenting out one of the assignments and running the program again. You'll find that each member variable that isn't assigned-to by you is initialized by the compiler to zero. Integer member variables are set to zero if you don't otherwise assign them. Remember that value types (such as integers) must be initialized; if you don't tell the constructor what to do, it sets innocuous values.



 Python   SQL   Java   php   Perl 
 game development   web development   internet   *nix   graphics   hardware 
 telecommunications   C++ 
 Flash   Active Directory   Windows