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

  • 04 November

    Pass 2D Array to Function in C++

    Table of ContentsWays to Pass a 2D Array to function in C++Pass a 2D Array to a Function by Passing Its PointerPass an Array to the Function by Decaying the Pointer to the ArrayPass a 2D Array to a Function in C++ Without Size by Passing Its ReferenceConclusion Two-dimensional arrays have rows and columns, storing […]

  • 02 November

    Count Decimal Places in C++

    Table of ContentsAccuracy V/S Precision in Counting Decimal Places in C++ ProgramsHow to Count Decimal Places in C++Example 1: Use String Functions to Find Precise Number of Decimal PlacesExample 2: Count Decimal Places Accurately for a NumberExample 3: Create a Program that divides two numbers and returns their decimal placesExample 4: Find the Number of […]

  • 02 November

    Check if String Is Empty in C++

    Table of ContentsWays to Check if String Is Empty in C++Using Empty() methodUsing the Equality OperatorUsing length() methodUsing size() methodConclusion A String is a combination of characters that can store both alphabets and numbers together. In C, there was no concept of string as a datatype so character arrays were used. In C++, this drawback […]

  • 03 October

    Get Filename from Path in C++

    Table of ContentsGet Filename From Path in C++Using find_last_of and substr methodsUsing TemplatesUsing filesysystem library [ C++ 17 ]Conclusion This article explains the various ways to get filename from path using C++ programs. The examples will also describe ways to remove extensions as well if such needs arise. Get Filename From Path in C++ Finding […]

  • 24 September

    Escape Percent Sign in printf Method in C++

    In this post, we will see how to escape percent sign in printf Method in C++. Escape percent sign in Printf Method in C++ printf() method uses percent sign(%) as prefix of format specifier. For example: To use number in prinf() method, we use %d, but what if you actually want to use percent sign […]

  • 15 September

    Remove Last Element from Vector in C++

    Table of ContentsWays to Remove Last Element from Vector in C++Using the vector::pop_back() function to remove last element from vector in C++Using the vector::resize() Function to Remove Last Element from Vector in C++Using the vector::rrase() Function to Remove Last Element from Vector in C++Conclusion Learn about how to remove last element from Vector in C++. […]

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.