Caroline Beltran
Caroline Beltran

Reputation: 918

Initialize a dynamic C array within a C++ initializer list

Most people will probably recommend that I use a std::vector or even a std::array but the custom array class below uses a C array and it works, I just need some explanation as to why it works.

For reference, here is a common way to initialize a dynamic C style array:

int* elements = new int[size];

Now below, we have our own custom array class that initializes a dynamic C style array within the initializer list. The problem is that I don't understand how the C array is being initialized within the initializer list.

class myArray 
{
public:

    myArray(int size) : size(size), elements(new int[size])
    {
        std::cout << "Constructed array of size " << size << std::endl;
    }

    ~myArray()
    {
        delete[] elements;
        std::cout << "Deleted elements" << std::endl;
    }

    int getSize() const { return size; }

private:
    int size;
    int* elements;  // our C style array
};

Thank you

UPDATE

I would like to clarify my question a little more. Below is the old fashioned "assignment" way that I would normally initialize the dynamic C array:

myArray(int size)
{
    elements = new int[size];
    // elements(new int[size]); // why will line only work in initializer list?
    std::cout << "Constructed array of size " << size << std::endl;
}

But please see the commented line. Why does that not work but it does work within the initializer list?

Upvotes: 0

Views: 1210

Answers (2)

marcinj
marcinj

Reputation: 49996

I don't understand how the C array is being initialized within the initializer list.

here:

myArray(int size) : size(size), elements(new int[size])

elements are basicly assigned value returned by new int[size]

You could rewrite it as :

myArray(int size)
{
    this->size = size;
    elements = new int[size];
    std::cout << "Constructed array of size " << size << std::endl;
}

[edit]

This:

// elements(new int[size]); // why will line only work in initializer list?

will not work in the function body, because in this place compiler thinks that you want to call a function named elements, but there is no such function.

The fact that it works in the initializer list is because that is how the language syntax was made.

Upvotes: 3

Titch
Titch

Reputation: 153

There are two initialization way. First way is trivial (literal) types initialization. Second way is the non-trivial type init.

For difference between this types see What is a non-trivial constructor in C++?

Also you can see, that trivial behavior may be different if you call default constructor manually or if it can be called implicitly. This will determine whether the memory is initialized (zerofill) with the allocation.

Some usefull information about hidden initialization you can find in book Anthony Williams "C++ Concurrency in Action: Practical Multithreading"

Upvotes: 1

Related Questions