What is the meaning of such an constructor?

I have a sample template class, but do not understand one line within it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
 template<typename T>
class Array
{
 public:
    Array(unsigned arraySize):
        data(0), size(arraySize)
    {
        if(size > 0)
            data = new T[size];
    }

    ~Array()
    {
        if(data) delete[] data;
    }

    void setValue(unsigned index, const T& value)
    {
        if(index < size)
            data[index] = value;
    }

    T getValue(unsigned index) const
    {
        if(index < size)
            return data[index];
        else
            return T();
    }

 private:
    T* data;
    unsigned size;
};


I do not understand the meaning of the following line. Array(unsigned arraySize): data(0), size(arraySize)

Can anyone explain the meaning of it?

Thanks,

Hailiang
That is called an initializer list.
That's an initializer list. It calls constructors for the data members from the : till the "constructor code" (typically started with {). When there's more constructors called, they are delimited with commas.

Array(unsigned arraySize): data(0), size(arraySize) {}
Corresponds to:
1
2
3
4
5
Array(unsigned arraySize)
{
      data = 0;
      size = arraySize;
}

or even:
Array(unsigned arraySize): data(0) {size = arraySize;}

Generally, use initializer lists whenever possible, since they are a lot more clear in what they try to achieve.


EDIT: Gah, R0mai beat me to it. :P
Last edited on
Thanks R0mai, and Kyon for your excellent example. I understand now.
Topic archived. No new replies allowed.