How to initialize an Array in Constructor in C++

How to initialize an array in Constructor in C++

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:

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.

Output :

0 0 0 0 0 0 0 0 0 0

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.

Output :

1 0 1 0 1 0 1 0 1 0

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.

Output :

2 4 1 5 4 7 8 0 9 6

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

Was this post helpful?

Related Posts

  • 19 May

    Get Type of Object in C++

    Table of ContentsWhy Should We Determine the Type of Object in C++: Dynamic DispatchingGet Type of Object in C++ConclusionWas this post helpful? C++ is an object-oriented language where we often interact with objects of different types. The object interaction becomes more interesting when we add runtime polymorphism to it. The runtime polymorphism, also known as, […]

  • 19 May

    Convert Vector to Array in C++

    Table of ContentsVectors and Arrays in C++Convert Vector to Arrays in C++Using the for loop to convert vector to array in C++Using the copy() function to convert vector to array in C++Using the transform() function to convert vector to array in C++Using the data() function to convert vector to array in C++Using the & operator […]

  • Write String to file in C++
    31 March

    Write String to File in C++

    Table of ContentsUsing the fstream Library to write String to File in C++Using the Insertion Operator (<<) With the fstream ObjectUsing the write() Function of the fstream LibraryUsing the fwrite() Function to write String to File in C++ConclusionWas this post helpful? The files are used to store the data permanently on a disk. This mitigates […]

  • Print Array in C++
    23 March

    Print Array in C++

    Table of ContentsIntroduction of ArraysDifferent Methods to Print an Array in C++print array in C++ by Traversing Indicesprint array in C++ Using for_each() Functionprint array in C++ Using Range-Based for Loopprint array in C++ Using Iteratorsprint array Using ostream_iterator() Function and copy() Functionprint array Using C++17 copy() Function and make_ostream_joiner() FunctionConclusionWas this post helpful? An […]

  • Print Vector C++
    23 March

    Print Vector in C++

    Table of ContentsPrint Vector in C++ Using IndicesPrint Vector in C++ Using Range-Based for LoopPrint Vector in C++ Using for_each() FunctionPrint Vector in C++ Using IteratorPrint Vector in C++ by Overloading the Insertion Operator (<<)Print Vector in C++ Using copy() FunctionConclusionWas this post helpful? This article discusses the vector and how to print vector in […]

  • Print Map in C++
    15 March

    Print Map in C++

    Table of ContentsMap vs Unordered MapPrint Map in C++ Using IteratorPrint Map in C++ Using Range-Based for LoopPrint Map in C++ by Overloading the ostream Insertion Operator (<<)Print Map in C++17 Using Structure Binding and Range-Based for LoopPrint Map in C++17 Using for_each() FunctionConclusionReferencesWas this post helpful? Maps in C++ store the data in form […]

Leave a Reply

Your email address will not be published.

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.