How to initialize Array of objects with parameterized constructors in C++
Array of Objects:
When a class is defined, only the specification for the object is defined; no memory or storage is allocated. To use the data and access functions defined in the class, you need to create objects.
Syntax:
ClassName ObjectName[number of objects];
Different methods to initialize the Array of objects with parameterized constructors:
- Using malloc(): To avoid the call of non-parameterised constructor, use malloc() method. “malloc” or “memory allocation” method in C++ is used to dynamically allocate a single large block of memory with the specified size. It returns a pointer of type void which can be cast into a pointer of any form.
#include <iostream>#define N 5usingnamespacestd;classTest {// private variablesintx, y;public:// parameterised constructorTest(intx,inty){this->x = x;this->y = y;}// function to printvoidprint(){cout << x <<" "<< y << endl;}};intmain(){// allocating dynamic array// of Size N using malloc()Test* arr = (Test*)malloc(sizeof(Test) * N);// calling constructor// for each index of arrayfor(inti = 0; i < N; i++) {arr[i] = Test(i, i + 1);}// printing contents of arrayfor(inti = 0; i < N; i++) {arr[i].print();}return0;}chevron_rightfilter_noneOutput:0 1 1 2 2 3 3 4 4 5
- Using new keyword: The new operator denotes a request for memory allocation on the Heap. If sufficient memory is available, the new operator initializes the memory and returns the address of the newly allocated and initialized memory to the pointer variable. Here, pointer-variable is the pointer of type data-type. Data-type could be any built-in data type including array or any user-defined data types including structure and class.
For dynamic initialization new keyword require non parameterised constructor if we add a parameterised constructor. So we will use a dummy constructor for it.
#include <iostream>#define N 5usingnamespacestd;classTest {// private variablesintx, y;public:// dummy constructorTest() {}// parameterised constructorTest(intx,inty){this->x = x;this->y = y;}// function to printvoidprint(){cout << x <<" "<< y << endl;}};intmain(){// allocating dynamic array// of Size N using new keywordTest* arr =newTest[N];// calling constructor// for each index of arrayfor(inti = 0; i < N; i++) {arr[i] = Test(i, i + 1);}// printing contents of arrayfor(inti = 0; i < N; i++) {arr[i].print();}return0;}chevron_rightfilter_noneOutput:0 1 1 2 2 3 3 4 4 5
If we don’t use the dummy constructor compiler would show the error given below
Compiler Error:
error: no matching function for call to ‘Test::Test()’ Test *arr=new Test[N]; - Using Double pointer (pointer to pointer concept): A pointer to a pointer is a form of multiple indirections, or a chain of pointers. Normally, a pointer contains the address of a variable. When we define a pointer to a pointer, the first pointer contains the address of the second pointer, which points to the location that contains the actual value as shown below.
Here we can assign a number of blocks to be allocated and thus for every index we have to call parameterised constructor using the new keyword to initialise.
#include <iostream>#define N 5usingnamespacestd;classTest {// private variablesintx, y;public:// parameterised constructorTest(intx,inty): x(x), y(y){}// function to printvoidprint(){cout << x <<" "<< y << endl;}};intmain(){// allocating array using// pointer to pointer conceptTest** arr =newTest*[N];// calling constructor for each index// of array using new keywordfor(inti = 0; i < N; i++) {arr[i] =newTest(i, i + 1);}// printing contents of arrayfor(inti = 0; i < N; i++) {arr[i]->print();}return0;}chevron_rightfilter_noneOutput:0 1 1 2 2 3 3 4 4 5
- Using Vector of type class: Vector is one of the most powerful element of Standard Template Library makes it easy to write any complex codes related to static or dynamic array in an efficient way. It takes one parameter that can be of any type and thus we use our Class as a type of vector and push Objects in every iteration of the loop.
Vectors are same as dynamic arrays with the ability to resize itself automatically when an element is inserted or deleted, with their storage being handled automatically by the container. Vector elements are placed in contiguous storage so that they can be accessed and traversed using iterators. In vectors, data is inserted at the end.
#include <iostream>#include <vector>#define N 5usingnamespacestd;classTest {// private variablesintx, y;public:// parameterised constructorTest(intx,inty): x(x), y(y){}// function to printvoidprint(){cout << x <<" "<< y << endl;}};intmain(){// vector of type Test classvector<Test> v;// inserting object at the end of vectorfor(inti = 0; i < N; i++)v.push_back(Test(i, i + 1));// printing object contentfor(inti = 0; i < N; i++)v[i].print();return0;}chevron_rightfilter_noneOutput:0 1 1 2 2 3 3 4 4 5
Recommended Posts:
- Extract unique objects by attribute from array of objects.
- Initialize a vector in C++ (5 different ways)
- Different ways to initialize a variable in C/C++
- Constructors in C++
- When are Constructors Called?
- C++ Internals | Default Constructors | Set 1
- C++ Interview questions based on constructors/ Destructors.
- When does compiler create default and copy constructors in C++?
- C++ Classes and Objects
- When are static objects destroyed?
- Passing and Returning Objects in C++
- How to restrict dynamic allocation of objects in C++?
- How to make a C++ class whose objects can only be dynamically allocated?
- Comparing String objects using Relational Operators in C++
- Read/Write Class Objects from/to File in C++
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

