×

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

Virtual base class in C++

Consider in a C++ program, there are 4 classes named class A, class B, class C, and class D. If class B and class c inherit properties from class A....

3 minutes read.

Classes and Objects in C++

When it comes to object-oriented programming, objects are the basic building blocks. Memory is taken up by objects, which contain data and methods or functions that operate on it. On...

3 minutes read.

C++ Encapsulation

The following two essential components are present in all C++ programmes: Functions are the parts of a programme that perform actions, and they are termed programme statements (code).Program data is the...

4 minutes read.

C++ Polymorphism

Polymorphism refers to the fact that something exists in several forms. Polymorphism, in simple terms, is the ability of a message to be presented in several formats. A real-life example...

4 minutes read.

C++ program to read string using cin.getline()

C++ program to read string using cin.getline() C++ getline() is a standard library feature for reading a string or a line from an input source. A getline() function gets characters from...

3 minutes read.

Factorial Program in C++

C++ Factorial Program: The product of all positive descending integers is the factorial of n. n! denotes the factorial of n. For instance: 5! = 5*4*3*2*1=120 4! = 4*3*2*1=24 In Combinations and Permutations, the...

4 minutes read.

Private Inheritance in C++

Private inheritance is an inheritance in object-oriented programming (OOP) languages where a subclass derives from a superclass. Still, the derived class does not inherit the public and protected members of...

7 minutes read.

What are local class and global class in C++

In C++, a class is a fundamental block that achieves object-oriented programming. The class holds its data members and member functions. Objects help to access the data elements and functions....

4 minutes read.

C++ Call by Value

In this article, we will discuss C++ Call by Value with their syntax, examples, use cases, advantages, and disadvantages. C++ Function A function is a set of statements that executes a task....

5 minutes read.

C++ Functions

In other programming languages, a function is referred to as a process or a subroutine. We can design functions to execute any task. A function can be used repeatedly. It...

5 minutes read.

Palindrome Using While Loop in C++

A palindrome is a word, number, phrase, or other sequence of letters that reads the same backward as forward, such as 101 or MOM. Like other programming languages, C++ also allows...

6 minutes read.

Program to convert infix to postfix expression in C++

Parentheses are frequently employed in mathematical formulas to make their interpretation easier to understand. However, with computers, parenthesis in an expression might lengthen the time it takes to find a...

7 minutes read.

Scope Resolution Operator vs this Pointer in C++

In this tutorial, we will compare the Scope Resolution operation to this Pointer in C++ language. Scope Resolution Operator The Scope Resolution Operator in C++ programming language is usually denoted by (::)....

3 minutes read.

C++ For loop

C++ loop Statement C++ Loop statement allows us to repeat the execution of a statement or group of statements multiple times. The statement(s) repeat execution within loop until the condition of loop...

2 minutes read.

Sum of all elements between k1’th and k2’th Smallest Elements

In this tutorial, we will look at how to determine sum of all given elements between two given indexes’ smallest elements. Assuming an array of integers and two numbers, k1...

2 minutes read.

Web Development in C++

Before learning above C++ web development, we need to learn about CGI What is CGI? CGI stands for common gateway interface. CGI is a standard that tells us how the exchange of...

4 minutes read.

Star pattern in C++ using For Loops

Star patterns are one of the most extensively utilized patterns in any programming language since they help to increase logical thinking and flow control understanding.In the C++ programming language, you...

3 minutes read.

Implementation of a Falling Matrix in C++

In many Hollywood and Bollywood movies, we might have seen a programmer who will be referred to as a hacker all the time for some random reason which the writer...

3 minutes read.

List back () function in C++ STL

The list::back () function of the C++ STL returns a direct reference to the last element in the list container. This function varies from list::end (), which just returns an...

2 minutes read.

How to Handle Divide by Zero Exception in C++

If you are a programmer or interested in coding then it is obvious that you face some illogical test cases. Suppose, you have written one program that calculates the factorial...

6 minutes read.