How to initialize Array of objects with parameterized constructors in C++
Last Updated :
19 Apr, 2022
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:
1. Using bunch of function calls as elements of array: It's just like normal array declaration but here we initialize the array with function calls of constructor as elements of that array.
C++
#include <iostream>
using namespace std;
class Test {
// private variables.
private:
int x, y;
public:
// parameterized constructor
Test(int cx, int cy)
{
x = cx;
y = cy;
}
// method to add two numbers
void add() { cout << x + y << endl; }
};
int main()
{
// Initializing 3 array Objects with function calls of
// parameterized constructor as elements of that array
Test obj[] = { Test(1, 1), Test(2, 2), Test(3, 3) };
// using add method for each of three elements.
for (int i = 0; i < 3; i++) {
obj[i].add();
}
return 0;
}
2. Using malloc(): To avoid the call of a non-parameterized 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.
C++
#include <iostream>
#define N 5
using namespace std;
class Test {
// private variables
int x, y;
public:
// parameterized constructor
Test(int x, int y)
{
this->x = x;
this->y = y;
}
// function to print
void print() { cout << x << " " << y << endl; }
};
int main()
{
// allocating dynamic array
// of Size N using malloc()
Test* arr = (Test*)malloc(sizeof(Test) * N);
// calling constructor
// for each index of array
for (int i = 0; i < N; i++) {
arr[i] = Test(i, i + 1);
}
// printing contents of array
for (int i = 0; i < N; i++) {
arr[i].print();
}
return 0;
}
Output: 0 1
1 2
2 3
3 4
4 5
3. 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 parameterized constructor if we add a parameterized constructor. So we will use a dummy constructor for it.
C++
#include <iostream>
#define N 5
using namespace std;
class Test {
// private variables
int x, y;
public:
// dummy constructor
Test() {}
// parameterized constructor
Test(int x, int y)
{
this->x = x;
this->y = y;
}
// function to print
void print() { cout << x << " " << y << endl; }
};
int main()
{
// allocating dynamic array
// of Size N using new keyword
Test* arr = new Test[N];
// calling constructor
// for each index of array
for (int i = 0; i < N; i++) {
arr[i] = Test(i, i + 1);
}
// printing contents of array
for (int i = 0; i < N; i++) {
arr[i].print();
}
return 0;
}
Output: 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];
4. 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 parameterized constructor using the new keyword to initialize.
C++
#include <iostream>
#define N 5
using namespace std;
class Test {
// private variables
int x, y;
public:
// parameterized constructor
Test(int x, int y)
: x(x)
, y(y)
{
}
// function to print
void print() { cout << x << " " << y << endl; }
};
int main()
{
// allocating array using
// pointer to pointer concept
Test** arr = new Test*[N];
// calling constructor for each index
// of array using new keyword
for (int i = 0; i < N; i++) {
arr[i] = new Test(i, i + 1);
}
// printing contents of array
for (int i = 0; i < N; i++) {
arr[i]->print();
}
return 0;
}
Output: 0 1
1 2
2 3
3 4
4 5
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.
C++
#include <iostream>
#include <vector>
#define N 5
using namespace std;
class Test {
// private variables
int x, y;
public:
// parameterized constructor
Test(int x, int y)
: x(x)
, y(y)
{
}
// function to print
void print() { cout << x << " " << y << endl; }
};
int main()
{
// vector of type Test class
vector<Test> v;
// inserting object at the end of vector
for (int i = 0; i < N; i++)
v.push_back(Test(i, i + 1));
// printing object content
for (int i = 0; i < N; i++)
v[i].print();
return 0;
}
Output: 0 1
1 2
2 3
3 4
4 5
Similar Reads
How to create a List with Constructor in C++ STL
Lists are sequence containers that allow non-contiguous memory allocation. As compared to vector, list has slow traversal, but once a position has been found, insertion and deletion are quick. Normally, when we say a List, we talk about doubly linked list. For implementing a singly linked list, we u
2 min read
How to Parse an Array of Objects in C++ Using RapidJson?
RapidJSON is an open-source C++ library for parsing and serializing JSON (JavaScript Object Notation) data. It is designed to be fast and efficient, with a focus on simplicity and ease of use. It is widely used in a variety of applications and is known for its fast performance and low memory overhea
4 min read
How to print size of array parameter in C++?
How to compute the size of an array CPP? C++ // A C++ program to show that it is wrong to // compute size of an array parameter in a function #include <iostream> using namespace std; void findSize(int arr[]) { cout << sizeof(arr) << endl; } int main() { int a[10]; cout << si
3 min read
How to create an Array of Objects in the Stack memory?
What is an Array of Objects? An array of objects is a data structure that stores a collection of objects of the same type. The objects in the array are stored in contiguous memory locations, and the array provides indexed access to the objects. This means that you can access an individual object in
6 min read
Why can't simple initialize (with braces) 2D std::array?
C++ provides a fixed-size sequence container named std::array. It is a useful alternative to C-style arrays, providing additional features such as bounds checking and iterators. We can also create a 2D version of the std::array where each element is an instance of std::array itself. However, when it
2 min read
How to Initialize a Static std::map<int, int> in C++
In C++, std::map<int, int> is a commonly used container that stores key-value pairs. There are scenarios where we may want to initialize a static std::map with predefined key-value pairs that remain constant throughout the program's execution. In this article, we will learn different methods t
4 min read
Different Ways to Initialize an unordered_set in C++
An unordered_set is an associated container available in the C++ Standard Template Library(STL) that is used for unique elements without any specific ordering, it internally uses the working principle of a hashtable to store elements. Different ways to Initialize an unordered_set in C++ Initializati
6 min read
How to Define the Constructor Outside the Class in C++?
A constructor is a special type of member function whose task is to initialize the objects of its class. It has no return type so can't use the return keyword and it is implicitly invoked when the object is created. Constructor is also used to solve the problem of initialization. It is called after
2 min read
Order of execution in initializer list in C++
Prerequisite: Classes, Constructors, Initializer list In this article, we will discuss the order of execution in the initializer list in C++. Generally, the order of execution is from top to bottom and left to right. But a rare condition arises where this rule fails is when the initializer list is u
2 min read
Passing a Vector to Constructor in C++
Just like any other data, we can also pass a vector to a constructor of the desired class. We can pass it by value or by reference. What we do with it depends on our requirement. The following are some of the common cases:Copy Data to Member VectorIf we want to store the copy of the vector in the cl
3 min read