Table of Contents
This article discusses methods of initializing an array in constructor in C++. Let us first discuss arrays and constructors in C++.
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 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 by taking user inputs.
Some of the most popular ways of initializing arrays are as follows:
1 2 3 |
int arr[6]={2,9,1,4,7,8}; |
1 2 3 |
int arr[]={2,9,1,4,7,8}; |
1 2 3 4 5 6 7 8 9 |
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 explicitly defined constructor then the compiler defines a default constructor which does not have any parameters and has an empty body. There are three types of constructors :
- Default constructor
- Parameterized Constructor
- Copy Constructor
We could have gone into further details on constructors but it deserves an article of its own.
Ways to initialize an array in Constructor in C++
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.
Initialize an array in Constructor 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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
#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 :
Initialize an array in Constructor 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.
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 |
#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 :
Further reading:
Initialize an array in Constructor 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 that 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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
#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 :
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
- https://www.cplusplus.com/forum/beginner/160453/
- https://www.modernescpp.com/index.php/initialization