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?