×

Initialize Array of objects with parameterized constructors in C++

Initialize Array of objects with parameterized constructors in C++

When a class is defined, only the specification for the object is specified; no memory or capacity is allocated. You need to build objects to use the data and access functions specified in the class.

Syntax:

ClassName ObjectName[number of objects];

Specific methods for initializing the Parameterized Constructors list of objects:

Using malloc(): Use malloc() method to avoid calling a non-parameterized constructor. The "Malloc" or "Memory Allocation" method in C++ is used to dynamically allocate the specified size of a single large block of memory. It returns a sort void pointer that can be thrown into a pointer of any kind.

#include <iostream>
#define P 5
using namespace std;
class Test
{
    // private variables
    int a, b;
public:
    // parameterised constructor
    Test(int a, int b)
    {
        this->a = a;
        this->b = b;
    }
    // function to print
    void print()
    {
        cout << a << " " << b << endl;
    }
};
int main()
{
    // allocating dynamic array
    // of Size N using malloc()
    Test* arr = (Test*)malloc(sizeof(Test) * P);
    // calling constructor
    // for each index of array
    for (int k = 0; k < P; k++)
          {
        arr[k] = Test(k, k + 1);
    }
    // printing contents of array
    for (int k = 0; k < P; k++)
           {
        arr[k].print();
    }
    return 0;
}

Output:

Initialize Array of objects with parameterized constructors in C++

Using Double pointer: The pointer to a pointer is a set of complex indirect or a pointer chain. A pointer typically holds the address of a variable. When we describe a pointer to a pointer, the first pointer contains the second pointer 's address, which points to the location containing the real value, as shown below. Now we can allocate a number of blocks to be assigned, so we have to call the parameterized constructor to initialize for each index using the new keyword.

#include <iostream>
#define T 10
using namespace std;
class Test {
          // private variables
          int s, t;
public:
          // parameterised constructor
          Test(int s, int t)
                   : s(s), t(t)
          {
          }
          // function to print
          void print()
          {
                   cout << s << " " << t << endl;
          }
};
int main()
{
          // allocating array using
          // pointer to pointer concept
          Test** arr = new Test*[T];
          // calling constructor for each index
          // of array using new keyword
          for (int i = 0; i < T; i++) {
                   arr[i] = new Test(i, i + 1);
          }
          // printing contents of array
          for (int i = 0; i < T; i++) {
                   arr[i]->print();
          }
          return 0;
}

Output:

Initialize Array of objects with parameterized constructors in C++

Using a new keyword: On the Heap, the new operator denotes a memory allocation request. If there is enough memory, the new operator identifies the memory and returns the newly allocated and configured memory address to the variable name. Here, point-variable is the information-type pointer. Data type could be any type of built-in data along with an array or any type of user-defined data such as structure and class.

If we add a parameterized constructor, a new keyword requires a non-parameterized constructor for dynamic initialization. So we're going to use a dummy constructor for that.

#include <iostream>
#define E 15
using namespace std;
class Test {
    // private variables
    int m, n;
public:
    // dummy constructor
    Test() {}
    // parameterised constructor
    Test(int m, int n)
    {
        this->m = m;
        this->n = n;
    }
    // function to print
    void print()
    {
        cout << m << " " << n << endl;
    }
};
int main()
{
    // allocating dynamic array
    // of Size N using new keyword
    Test* arr = new Test[E];
    // calling constructor
    // for each index of array
    for (int j = 0; j < E; j++) {
        arr[j] = Test(j, j + 1);
    }
    // printing contents of array
    for (int j = 0; j < E; j++) {
        arr[j].print();
    }
    return 0;
}

Output:

Initialize Array of objects with parameterized constructors in C++

Related Topics

C++ 11 vs C++ 14 vs C++ 17

C++ is a language that is used to create a high-performance application. C++ 11, C++ 14, and C++ 17 are the different version of C++. There are some differences between...

1 minute read.

C++ Variable

In this article, we will discuss variables in C++ with their types and examples. What are Variables? Variables are specific memory storage spaces that hold a value. During the execution of a...

4 minutes read.

C++ Structs

We frequently encounter scenarios in which we must store a bunch of data, whether of comparable or dissimilar data kinds. Arrays are used to hold a group of data of...

6 minutes read.

Inheritance Program in C++

What is Inheritance? Inheritance is the ability of a class to inherit traits and properties from another class. One of the most crucial aspects of Object-Oriented Programming is inheritance. The ability or...

9 minutes read.

Convex hull Algorithm in C++

The intersection of all convex sets containing a certain subset of a Euclidean space, or alternatively, the set of all convex combinations of points in the subset, defines the convex...

4 minutes read.

Scope Resolution Operator in C++

The scope resolution operator and its different usage in the C++ programming language will be discussed in this section. The scope resolution operator is used to refer to an out-of-scope...

6 minutes read.

Object Slicing in C++

In this article, we will learn about Object slicing. When an object from a derived class is assigned to an object from a base class in C++, these extra attributes...

3 minutes read.

C++ Prime number program

In this lesson, you'll learn how to verify whether a given number is a prime number or not in C++, and you'll obtain code to do it. What is the definition...

3 minutes read.

How to create the Processes with Fork in C++

 In this article, we are going to explain the different methods that help us to create processes with a fork(). There are two methods to do so. These methods are...

2 minutes read.

C++ if-else

C++ if else Control Statement if else control statement in C++ is used to control the program flow in a two-way direction. When condition returns a true value, then the program executes if condition block otherwise...

1 minute read.

std::distance() in C++

The primary function of std::distance is to facilitate the total number of elements if we have two iterators. It is defined inside the header files. It has both magnitude and...

2 minutes read.

DES in C++

The popularity of the Data Encryption Standard (DES) is slightly declining as a result of the discovery that DES is susceptible to very strong attacks. Since DES is a block cypher,...

3 minutes read.

C++ User Defined Exceptions

Overriding and inheriting exception class capabilities may be used to define the new exception. Exception handling can also be used with classes. We may also make an exception for user-defined...

4 minutes read.

Backtracking Time Complexity in C++

Introduction to Backtracking Backtracking is an important part of programming languages, and with the help of backtracking, we can do many operations in an advanced data structure. For doing major operations,...

4 minutes read.

C++ Identifier

In a program, C++ identifiers relate to the names of variables, functions, arrays, and other user-defined data types that the programmer has developed. They are a prerequisite for learning any...

4 minutes read.

Observer Design Pattern in C++

The Observer design pattern is a behavioural design pattern that allows an object (known as the subject) to notify other objects (known as observers) when its state changes. This is...

3 minutes read.

Loops in C++

A loop statement in most programming languages allows us to execute a statement or a collection of statements numerous times. Control structures of programming languages vary, allowing for more complex...

6 minutes read.

Decimal to Binary in C++

What is the meaning of Decimal Numbers? Decimal numbers range from 0 to 9, there are a total of ten digits between 0 and 9. Any number with more than two...

3 minutes read.

Initialize Array of objects with parameterized constructors in C++

Initialize Array of objects with parameterized constructors in C++ When a class is defined, only the specification for the object is specified; no memory or capacity is allocated. You need to...

3 minutes read.

C++ String

A string is a collection of characters. C++ programming language supports both C string as well as standard C++ library string. In C++, string is an object of std::string class. C Style String The C style...

5 minutes read.