Initialization of class data. Constructor. Constructor by default

Initialization of class data. Constructor. Constructor by default


Contents


1. What is the constructor? What are the differences between class methods and constructors?

Syntactically, a method is similar to the constructor. The constructor initializes the class object, when it is created. The name of the constructor is the same as a class name. Constructor cannot return a type, which is specified explicitly.

As a rule, the constructor is applied for:

  • setting of the initial values in the variables of class instance;
  • performing some initial operations that are needed to creating the fully formed object.

 

2. What is a general form of a constructor?

The general form of constructor is as follows:

access class_name(parameters)
{
    // constructor body
}

where

  • access – access modifier. In the most cases it is the “public” modifier. If the constructor is called outside the boundaries of a class, then it must be as “public“.
  • parametersthe list of parameters, which constructor takes. Parameters list can be empty.

An example of declaration the constructor of class MyPoint (see previous paragraphs). In the given constructor two parameters are taken. The names of these parameters: newx and newy. These parameters initializes the internal variables x and y of the class.

...

public MyPoint(int newx, int newy)
{
    x = newx;
    y = newy;
}

...

// using of the declared constructor, when class instance is created
MyPoint p = new MyPoint(5,8);

 

3. How many constructors can be specified in the class?

Any class can contain any number of constructors, which must differ one from another by the number of parameters and/or by the types of parameters.

 

4. What means the constructor by default?

If you did not declare constructor in a class, the C# language automatically will create the constructor by default. This constructor initializes all variables of class instance by their values by default.

For most data types, the default value is zero, for type boolfalse, for the reference type – empty value.

Example. Let there be given class MyBook, that contains data only. In the class are not declared constructors. Anyway, when you create an instance of the class (operator new), the default constructor is called.

...

class MyBook
{
    private string Title;
    private string Author;
    private int year;
    private float price;
}

...

// using of class in the program
// the constructor by default MyBook() is called, which doesn't declared explicitly
MyBook mb1 = new MyBook();

...

 

5. Example of initializing of the class using a constructors.

Let there be given a definition of class MyBook. In the class MyBook are described two constructors. One of them is the constructor without parameters. Second constructor takes four parameters, which fill the corresponding internal fields of MyBook class.

...

class MyBook
{
    // class fields - are declared as "private"
    private string Title;
    private string Author;
    private int year;
    private float price;

    // constructor without parameters
    public MyBook()
    {
        Title = "";
        Author = "";
        year = 1900;
        price = 0.00f;
    }

    // constructor with four parameters
    public MyBook(string t, string a, int y, float p)
    {
        Title = t;
        Author = a;
        year = y;
        price = p;
    }
}

...

// using of the constructors when class data (fields) are initialized
MyBook mb1 = new MyBook();
MyBook mb2 = new MyBook("Title-1", "Author-1", 2000, 3.99f);

 

6. What constructors are called parameterized?

Parameterized constructors are constructors that accept one or more parameters.

 

7. Overloading of constructors? Example

A constructor, like any method, can be overloaded. That is, there can be several constructors in a class, which differ in the types and (or) number of parameters.

Example. The class Time is declared, which implements the time: hours, minutes, seconds. The class implements 4 constructors with a different number of parameters. The source code for the class is as follows:

// class that implements time
class Time
{
    int hour; // hours
    int min; // minutes
    int sec; // seconds

    // constructor without parameters
    public Time()
    {
        hour = min = sec = 0;          
    }

    // constructor with 1 parameter - it sets only hours
    public Time(int hour)
    {
        this.hour = hour;
        min = sec = 0;
    }

    // constructor with 2 parameters - it sets hours, minutes
    public Time(int hour, int min)
    {
        this.hour = hour;
        this.min = min;
        sec = 0;
    }

    // constructor with 3 parameters - it sets hours, minutes, seconds
    public Time(int hour, int min, int sec)
    {
        this.hour = hour;
        this.min = min;
        this.sec = sec;
    }

    // access methods
    public int GetHour() { return hour; }
    public int GetMin() { return min; }
    public int GetSec() { return sec; }
}

Using the Time class in another method (program code):

// using the Time class
Time t0 = new Time(); // call the constructor without parameters 00:00:00
Time t1 = new Time(8); // call the constructor with 1 parameter 08:00:00
Time t2 = new Time(5, 23); // call the constructor with 2 parameters 05:23:00
Time t3; // only declaration of a reference to a class of type Time
t3 = new Time(10, 20, 45); // object creation, constructor call with 3 parameters 10:20:45

// check
int h, m, s;

h = t0.GetHour(); // h = 0
m = t0.GetMin(); // m = 0

h = t1.GetHour(); // h = 8

h = t2.GetHour(); // h = 5
m = t2.GetMin(); // m = 23
s = t2.GetSec(); // s = 0

h = t3.GetHour(); // h = 10
m = t3.GetMin(); // m = 20
s = t3.GetSec(); // s = 45

 

8. Is it possible to call another constructor from one constructor?

Yes, it is. This is implemented using the ‘this’ keyword. The keyword this is a reference to the current class. That is, this is the name of the current class, which means it can be used as a constructor.

 

9. How is it possible call one constructor from another? General form

The general form of calling from one constructor to another in a class that named as ClassName:

class ClassName
{
    // this is constructor
    ClassName(parameters_list1) : this(parameters_list2)
    {
        // the body of ClassName() constructor
    }
}

In this case, the constructor is first called

this(parameters_list2)

and then the constructor is called

ClassName(parameters_list1)

The body of the ClassName constructor may be empty.

 

10. An example of calling one constructor from another

The example implements the Time class, which describes the time. There are several constructors in the class. Each of them is initialized differently.

Class listing is as follow

// class, that implements time
class Time
{
    int hour; // hours
    int min; // minutes
    int sec; // seconds

    // constructor without parameters — initialized with a 3-parameter constructor
    public Time() : this(0, 0, 0)
    {
        // the body of constructor is empty
    }

    // constructor with a single parameter - it sets only hours
    public Time(int hour) : this(hour, 0, 0)
    { }

    // constructor with 2 parameters - it sets hours and minutes
    public Time(int hour, int min) : this(hour, min, 0)
    { }

    // constructor with 3 parameters - it sets hours, minutes and seconds
    public Time(int hour, int min, int sec)
    { }

    // a constructor that receives an object reference as a parameter
    public Time(Time t) : this(t.GetHour(), t.GetMin(), t.GetSec())
    { }

    // access methods
    public int GetHour() { return hour; }
    public int GetMin() { return min; }
    public int GetSec() { return sec; }
}

Using a class in another program code (method)

// using the Time class
Time t0 = new Time(); // call the constructor without parameters 00:00:00
Time t1 = new Time(8); // call the constructor with 1 parameter 08:00:00
Time t2 = new Time(7, 17); // call the constructor with 2 parameters 07:17:00
Time t3; // only declaration of a reference to a class of type Time
t3 = new Time(7, 10, 15); // object creation, constructor call with 3 parameters 7:10:15
Time t4 = new Time(t3); // call the constructor that takes a class object as parameter

// check
int h, m, s;

h = t0.GetHour(); // h = 0
m = t0.GetMin(); // m = 0

h = t1.GetHour(); // h = 8

h = t2.GetHour(); // h = 7
m = t2.GetMin(); // m = 17
s = t2.GetSec(); // s = 0

h = t3.GetHour(); // h = 7
m = t3.GetMin(); // m = 10
s = t3.GetSec(); // s = 15

h = t4.GetHour(); // h = 7
m = t4.GetMin(); // m = 10
s = t4.GetSec(); // s = 15


Related topics