The Wayback Machine - https://web.archive.org/web/20240826113240/https://www.geeksforgeeks.org/how-to-initialize-array-of-objects-with-parameterized-constructors-in-c/
Open In App

How to initialize Array of objects with parameterized constructors in C++

Last Updated : 19 Apr, 2022
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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

Parameterized Constructor in C++
In C++, parameterized constructor is a type of constructor that can accept arguments. Parameterized Constructors make it possible to pass arguments to initialize an object when it is created. To create a parameterized constructor, simply add parameters to it the way you would to any other function. When you define the constructor’s body, use the pa
4 min read
Extract unique objects by attribute from array of objects
Given an array of objects and the task is to return the unique object by the attribute. Examples: Input: [ { name: 'Geeks', id: 10 }, { name: 'GeeksForGeeks', id: 10 }, { name: 'Geeks', id: 20 }, { name: 'Geeks', id: 10 } ]Output:[ { name: 'Geeks', id: 10 }, { name: 'GeeksForGeeks', id: 10 } ]Approach: Let's assume that name is an attribute that di
4 min read
Distribute M objects starting from Sth person such that every ith person gets arr[i] objects
Given an array arr[] consisting of N integers (1-based indexing) and two integers M and S, the task is to distribute M objects among N persons, starting from the position S, such that the ith person gets at most arr[i] objects each time. Examples: Input: arr[] = {2, 3, 2, 1, 4}, M = 11, S = 2Output: 1, 3, 2, 1, 4Explanation: The distribution of M (
8 min read
Number of ways to arrange K different objects taking N objects at a time
Given two integers K and N, the task is to count the number of ways to arrange K different objects taking N objects at a time. Each arrangement contains one object at most once. The answer can be very large so return the answer modulo 109 + 7.Note: 1 &lt;= N &lt;= K &lt;= 105. Prerequisites: Factorial of a number, Compute nCr % pExamples: Input : N
11 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 comes to initializing a 2D std::array, things can
3 min read
When Does Compiler Create Default and Copy Constructors in C++?
A constructor is a special type of member function of a class that initializes objects of a class. In C++, Constructor is automatically called when an object(instance of a class) is created. There are 3 types of constructors in C++ Default ConstructorCopy constructorParameterized ConstructorIn C++, the compiler creates a default constructor if we d
3 min read
C++ Interview questions based on constructors/ Destructors.
1. What is destructor? Ans. Destructor is a member function which is called when an object is deleted/destroyed or goes out of scope. class String { private: char* s; int size; public: String(char*); // constructor ~String(); // destructor }; 2. What is the purpose of using a destructor in C++? Ans. The main purpose of destructor is to free all the
3 min read
When are Constructors Called?
When are the constructors called for different types of objects like global, local, static local, dynamic? 1) Global objects: For a global object, constructor is called before main() is called. For example, see the following program and output: C/C++ Code #include&lt;iostream&gt; using namespace std; class Test { public: Test(); }; Test::Test() { c
3 min read
A Comprehensive Guide to Constructors in C++: Everything You Need to Know
In C++, constructors are special member functions of a class that are automatically called when an object of the class is created. They are used to initialize objects. Constructors have the same name as the class and do not have a return type. What is a Constructor?A constructor is a special member function of a class that initializes objects of th
15+ min read
Types of Constructors in C++
In C++, there are several types of constructors, each serving a different purpose. Constructors can be classified based on in which situations they are being used. There are 4 types of constructors in C++: Default Constructor: No parameters. They are used to create an object with default values.Parameterized Constructor: Takes parameters. Used to c
13 min read
Constructors in C++
Constructor in C++ is a special method that is invoked automatically at the time an object of a class is created. It is used to initialize the data members of new objects generally. The constructor in C++ has the same name as the class or structure. It constructs the values i.e. provides data for the object which is why it is known as a constructor
7 min read
Importance of Constructors in C++
Constructors are special member functions in C++ that are invoked automatically when an object of a class is created. Their primary role is to initialize objects. In this article, we will learn all the factors that makes the constructor important in C++. Table of Content Initialization of ObjectsResource ManagementOverloading ConstructorsDefault Co
8 min read
Default Constructors in C++
A constructor without any arguments or with the default value for every argument is said to be the Default constructor. A constructor that has zero parameter list or in other sense, a constructor that accepts no arguments is called a zero-argument constructor or default constructor. If default constructor is not defined in the source code by the pr
4 min read
Efficient way to initialize a priority queue
STL Priority Queue is the implementation of Heap Data Structure. By default, it's a max heap, and can be easily for primitive data types. There are some important applications of it which can be found in this article. Priority queue can be initialized in two ways either by pushing all elements one by one or by initializing using their constructor.
7 min read
Different methods to initialize a Linked List
Like arrays, a Linked List is a linear data structure. Unlike arrays, linked list elements are not stored at a contiguous location; the elements are linked using pointers. They include a series of connected nodes. Here, each node stores the data and the address of the next node. There are two methods to copy the linked list into another linked list
15+ 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++ Initialization using the default constructorInitialization usi
6 min read
Different Ways to Initialize a Map in C++
Map is an associative container available in the C++ Standard Template Library(STL) that is used to store key-value pairs. Let's see the different ways to initialize a map in C++. Initialization using assignment and subscript operatorInitialization using an initializer listInitialization using an array of pairsInitialization from another map using
5 min read
Different Ways to Initialize a List in C++ STL
Prerequisite: List in C++ Lists are sequence containers that allow non-contiguous memory allocation The following are the different ways to create and initialize a List in C++ STL. Initializing an empty List and pushing values one by oneSpecifying List size and initializing all valuesInitializing List like the arraysInitializing a list from an arra
6 min read
How to Initialize 3D Vector in C++ STL?
Prerequisite: Vector in C++ Vectors in C++ are the same as arrays with dynamic sizes having the ability to resize themselves, we can insert and remove elements from the end. 3-D Vector A 3D vector is a type of vector having 3 Dimensions means a vector storing a 2-D vector inside it, similar to a 2-D array. There are a few methods to initialize a 3D
3 min read
How to Initialize and Compare Strings in Java?
String is one of the most basic data types and it is widely used in storing and manipulating pieces of text. One of the fundamental features of strings in Java is their immutability that is once a string is created, it will never be changed. Immutability creates two general ways of initialization with strings in Java using the String Pool. This art
5 min read
7 ways to Initialize Vector in C++
Vectors in C++, like Arrays, are one of the most extensively used entities and to initialize vectors in C++ is one of the most common issues that users face. One of the most commonly used methods for vector initialization is the Array style. But C++, along with this, provides several different methods to initialize a vector. In this post, we have l
6 min read
How to Initialize a Static std::map&lt;int, int&gt; in C++
In C++, std::map&lt;int, int&gt; 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 to initialize a static std::map&lt;int, int&gt; in
4 min read
Different Ways to Initialize an unordered_map in C++
unordered_map is an associated container available in the C++ Standard Template Library(STL) that is used to store key-value pairs. It internally uses the working principle of a hashmap to store key-value pairs. Different ways to initialize an unordered_map in C++: Initialization using assignment and subscript operatorInitialization using an initia
5 min read
Different Ways to Initialize an Set in C++
A set is an associative container available in the C++ Standard Template Library(STL) that is used for unique elements in a specific order, it internally uses the working principle of a Binary Search Tree to store elements. Different Ways to Initialize a set in C++: Initialization using the default constructor.Initialization using initializer list.
5 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 the array using its index, just like you would wit
6 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 overhead. It is a popular choice for parsing and serializ
4 min read
Find maximum height pyramid from the given array of objects
Given n objects, with each object has width wi. We need to arrange them in a pyramidal way such that : Total width of ith is less than (i + 1)th.Total number of objects in the ith is less than (i + 1)th. The task is to find the maximum height that can be achieved from given objects. Examples :Input : arr[] = {40, 100, 20, 30}Output : 2Top level : 3
11 min read
Array of Objects in C++ with Examples
An array in C/C++ or be it in any programming language is a collection of similar data items stored at contiguous memory locations and elements can be accessed randomly using indices of an array.  They can be used to store the collection of primitive data types such as int, float, double, char, etc of any particular type. To add to it, an array in
5 min read
Static Objects in C++
Prerequisite: Static Keyword in C++ An object becomes static when a static keyword is used in its declaration. Static objects are initialized only once and live until the program terminates. They are allocated storage in the data segment or BSS segment of the memory. C++ supports two types of static objects: Local Static ObjectsGlobal Static Object
3 min read
2D Transformation in Computer Graphics | Set 1 (Scaling of Objects)
We can use a 2 × 2 matrix to change or transform, a 2D vector. This kind of operation, which takes in a 2-vector and produces another 2-vector by a simple matrix multiplication, is a linear transformation. By this simple formula, we can achieve a variety of useful transformations, depending on what we put in the entries of the matrix. For our purpo
5 min read
Practice Tags :