Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is it possible to intialize array filled with zeros in member initializer list?

I need to define an empty constructor of class Array, which has one argument that contains value of parameter m. It needs to allocate memory for m elements in an array and initialize it with zeros.

class Array{
protected:
 int* data;
 int m;

public:
 Array(int m);
};

Is it possible to initialize it with zeros in member initializer list, or it can’t be done except with a for loop in the body of this constructor. I defined this constructor like this:

Array::Array(int m):m(m),data(new int[m]){}

but of course its filled with random thrash values leftover in the memory.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You may write either

Array::Array(int m): m( m ), data( new int[m]() )
{
}

or

Array::Array(int m): m( m ), data( new int[m]{} )
{
}

It is better to declare the data member m as having the type size_t instead of the type int.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading