Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 6

Initializing an Array in Constructor in C++

Introduction

Arrays
Arrays are fundamental data structures, it is basically a collection of elements of the same
data type stored in a contiguous memory location. Arrays in C++ can be made up of
primitive data types such as int.float,double,char,long, long long double double etc., and
also with class, structs, pointers etc. which are derived or user defined data types. Arrays
can have a single dimension or can be multidimensional.

In many use cases when working with arrays one may need to initialize the array. Now,
this initialization also depends upon the use case, whether the requirement is to initialize
with a same single element or predefined different values or maybe taking user inputs.
Some of the most popular ways of initializing arrays are as follows:

Int arr[6]={2,9,1,4,7,8};

Int arr[]={2,9,1,4,7,8};

Int arr[5];
arr[0]=2;
arr[1]=9;
arr[2]=1;
arr[3]=4;
arr[4]=7;
arr[4]=8;

Initializing an array in a constructor is one special use case which we will discuss in this
article.

Constructors of a Class
Constructors are special member functions of a class which are automatically called when
an instance of the class is created. It has the same name as the class itself. What makes it
stand out from other member functions of class is that it does not have any return type. If
there is no constructor explicitly made then the compiler makes use of a default
constructor which does not have any parameters and has an empty body. There are three
types of constructors : Default constructor, Parameterized Constructor and Copy
Constructor. We could have gone into further details on constructors but it deserves an
article of its own.

So now, when we have all the basic concepts refreshed we can go on with the different
ways we can initialize an array inside a constructor of a class.

Initializing with std::fill()


In most cases we need to initialize the whole array with just one same single element. In
C++ standard template library (STL) we have std::fill() function which is a function that
fills any range based container with a value that matches with the data type of the
container. Thus std::fill() can fill any container like vectors, sets, maps and for our case
arrays. One special point to note is that when we provide range values in the function’s
parameters, the starting index is selected however the ending index is not selected. We
can mathematically express the range from the above definition as [begin,end) where
begin and end are indexes marking the first and last element of the range.

Let us now see the following code that will give us an idea of how it is to be
implemented. In this example, we define a structure: numbers with a data member arr
with a size of 10. And in its constructor we use the std::fill() function to initialize it.

#include<bits/stdc++.h>

using namespace std;

struct numbers
{
int arr[10];
numbers() //Constructor of the struct
{
fill(arr,arr+10,0);
}
};
int main() //Driver Function
{
numbers *nb=new numbers();
for(int i=0;i<10;i++)
{
cout<<nb->arr[i]<<" ";
}cout<<endl;
return 0;
}

Output :

0000000000

Initializing using for loop


In the previous example, we understood how easily we can initialize the array
using an inbuilt function to initialize the whole array with just one single number.
Using fill() function is just an elegant and simpler way to use when we have to
initialize it with only one element. However, a simple for loop could also have
done the task. But for loops have a better implementation when the requirement is
to initialize the array with some conditions. As we can initialize the array using the
for loop based on those conditions. To understand this concept, let us take an
example.

Let us suppose we have to initialize the array such that odd indexes have ‘0’ and
even indexes have ‘1’ of the array. In such a case we cannot use the fill() method
but we can do it conveniently using the for loop as shown in the following code
#include<bits/stdc++.h>

using namespace std;

struct numbers
{
int arr[10];
numbers() //constructor of the struct
{
for(int i=0;i<10;i++)
{
arr[i]=(i%2==0)?1:0; //Conditions Required
}
}
};
int main() //Driver Function
{
numbers *nb=new numbers();
for(int i=0;i<10;i++)
{
cout<<nb->arr[i]<<" ";
}cout<<endl;
return 0;
}

Output :

1010101010

Initializing arrays using Member Initializer List


The member initializer list is another useful tool in C++, which could help us in
initialization of an array in the constructor. Member Initializer list is a list of data
members with their initialized value which are in between a semicolon (:) and the
main body of the constructor. Initializer Lists have numerous applications which
includes initialization of const data members which are not static in nature
enabling us to initialize it even when not having an assigned memory. It also helps
in initializing referenced data members, objects of an inherited class and when the
name of the data member is the same as that of the parameter.

The most useful advantage of using member initializer lists is the efficiency in
performance. It reduces the normal workflow of the compiler from Constructor to
Assignment and then Deconstructor to just Copy Constructor followed by
Deconstructor. This may look as a minor change but in micro computers or big
data real systems these small tweaks may improve the overall performance by
great margin.

To illustrate the use of member initializer lists, let us go through the following
piece of code.

#include<bits/stdc++.h>

using namespace std;

struct numbers
{
int arr[10];
numbers():arr{2,4,1,5,4,7,8,0,9,6} //Member Initializer List
{}
};
int main() //Driver Function
{

numbers *nb=new numbers();


for(int i=0;i<10;i++)
{
cout<<nb->arr[i]<<" ";
}cout<<endl;
return 0;
}

Output :
2415478096

Conclusion
These were the different ways we can initialize arrays in constructors. We have
discussed various different use cases which can be helpful in specific applications.
For simple one data element entry standard function std::fill() can be used, for
condition based initialization for loops can be used and for efficient initialization
member initializer lists can be used.

This is all about Initializing arrays in Constructors in C++.

Hope you have learned something new and enjoyed reading the article. Stay tuned
for more such articles. Happy learning!

References
1. https://www.cplusplus.com/forum/beginner/160453/
2. https://www.modernescpp.com/index.php/initialization

You might also like