Table of contents
1.
Introduction
2.
What Is An Object?
3.
What Is An Array Of Objects?
4.
Declaration Of Array Of Objects In C++
5.
Initializing Array Of Objects In C++
6.
C++ example with new operator
7.
C++ example with malloc
8.
Advantages of Array of Objects
9.
Disadvantages of Array of Objects
10.
Frequently Asked Questions
10.1.
Can we have an array of objects with different data types?
10.2.
How do you dynamically resize an array of objects?
10.3.
Can we pass an array of objects to a function?
11.
Conclusion
Last Updated: Nov 23, 2024
Easy

Array of Objects in C++

Author Rahul Singh
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

In C++, an array of objects allows you to store and work with multiple objects of the same class in a structured manner. It provides a convenient way to group related objects together and perform operations on them collectively. With the help of an array of objects, you can efficiently manage and manipulate a collection of objects with similar properties and behaviors. 

Array of Objects in C++

In this article, we will discuss the concept of an array of objects in C++, like its declaration, initialization, and code examples. 

What Is An Object?

In C++, an object is an instance of a class. It is a real-world entity that has attributes (data members) & behaviors (member functions). An object is created from a class template & occupies memory space. Each object has its own unique set of data members, which can be accessed & modified using the object's member functions. Objects allow you to encapsulate related data & functions into a single unit, promoting code organization & reusability. They form the foundation of object-oriented programming (OOP) in C++, enabling you to model real-world scenarios & create modular, maintainable code.

What Is An Array Of Objects?

An array of objects in C++ is a collection of objects of the same class type stored in contiguous memory locations. It allows you to create & manage multiple objects with similar properties & behaviors in a single data structure. Each element in the array represents an individual object, and you can access these objects using their respective indices. By using an array of objects, you can efficiently perform operations on multiple objects simultaneously, like initialization, data manipulation, and iteration. This helps in code organization, reduces redundancy, and simplifies common tasks when working with a group of related objects.


For example: 


class Student {
public:
    string name;
    int age;
    void displayInfo() {
        cout << "Name: " << name << ", Age: " << age << endl;
    }
};


int main() {
    const int SIZE = 3;
    Student students[SIZE];


    for (int i = 0; i < SIZE; i++) {
        cout << "Enter name & age for student " << i + 1 << ": ";
        cin >> students[i].name >> students[i].age;
    }


    cout << "\nStudent Information:" << endl;
    for (int i = 0; i < SIZE; i++) {
        students[i].displayInfo();
    }


    return 0;
}
You can also try this code with Online C++ Compiler
Run Code


In this example, we define a `Student` class with `name` and `age` attributes and a `displayInfo()` member function. We create an array of `Student` objects called `students` with a size of 3. We then use loops to input data for each student object and display their information.

The array of objects helps us store and manage multiple `Student` objects efficiently, providing a structured way to work with related data.

Declaration Of Array Of Objects In C++

To declare an array of objects in C++, you need to specify the class name followed by the array name and the desired size of the array. The syntax for declaring an array of objects is:

ClassName arrayName[size];


Here, `ClassName` is the name of the class for which you want to create an array of objects, `arrayName` is the name you choose for the array, and `size` is the number of objects you want to store in the array.


Let's look at an example:

class Rectangle {
private:
    int length;
    int width;


public:
    void setDimensions(int l, int w) {
        length = l;
        width = w;
    }


    int getArea() {
        return length * width;
    }
};

int main() {
    const int SIZE = 5;
    Rectangle rectangles[SIZE];


    // Further code to initialize and use the array of objects...


    return 0;
}
You can also try this code with Online C++ Compiler
Run Code


In this example, we declare an array of `Rectangle` objects named `rectangles` with a size of 5. Each element of the `rectangles` array represents an individual `Rectangle` object.

It's important to note that when you declare an array of objects, the default constructor of the class is called for each object in the array. If the class doesn't have a default constructor, you need to explicitly define one or use other initialization techniques.

Initializing Array Of Objects In C++

After declaring an array of objects, you need to initialize the objects with appropriate values. There are several ways to initialize an array of objects in C++, like:

1. Using the default constructor: If the class has a default constructor (a constructor that takes no arguments), you can simply declare the array, and each object will be initialized with the default constructor.

   ClassName arrayName[size];


For example:

   Rectangle rectangles[5];


2. Using an initialization list: You can use an initialization list to provide initial values for each object in the array at the time of declaration.

   ClassName arrayName[size] = { { arguments_for_object1 }, { arguments_for_object2 }, ... };


For example:

   Rectangle rectangles[3] = { {3, 4}, {5, 6}, {7, 8} };


In this case, each object in the `rectangles` array is initialized with the provided length and width values.


3. Using a loop to initialize objects: You can use a loop to iterate over the array and initialize each object individually.

   for (int i = 0; i < size; i++) {
       // Initialize each object using member functions or assignment
       arrayName[i].memberFunction(arguments);
       arrayName[i].dataMember = value;
   }

   For example:


   for (int i = 0; i < 5; i++) {
       rectangles[i].setDimensions(i+1, i+2);
   }

 

In this case, each `Rectangle` object in the `rectangles` array is initialized with different length and width values using the `setDimensions()` member function.

C++ example with new operator

In C++, you can dynamically allocate an array of objects using the `new` operator. This allows you to create an array of objects at runtime and provides more flexibility in terms of size and memory management.

Let’s discuss an example that shows the use of the `new` operator to create an array of objects:

#include <iostream>
using namespace std;


class Student {
private:
    string name;
    int age;

public:
    Student(string n, int a) {
        name = n;
        age = a;
    }


    void displayInfo() {
        cout << "Name: " << name << ", Age: " << age << endl;
    }
};


int main() {
    int size;
    cout << "Enter the number of students: ";
    cin >> size;

    Student* students = new Student[size];

    string name;
    int age;
    for (int i = 0; i < size; i++) {
        cout << "Enter name and age for student " << i + 1 << ": ";
        cin >> name >> age;
        students[i] = Student(name, age);
    }


    cout << "\nStudent Information:" << endl;
    for (int i = 0; i < size; i++) {
        students[i].displayInfo();
    }


    delete[] students;


    return 0;
}
You can also try this code with Online C++ Compiler
Run Code


Output

Enter the number of students: 2
Enter name and age for student 1: Harsh 6
Enter name and age for student 2: Ria 23
Student Information:
Name: Harsh, Age: 6
Name: Ria, Age: 23


In this example:

1. We define a `Student` class with `name` and `age` attributes and a constructor that takes these values as parameters.
 

2. In the `main()` function, we dynamically allocate an array of `Student` objects using the `new` operator: `Student* students = new Student[size];`. The size of the array is determined by the user input.
 

3. We use a loop to input each student's name and age. Inside the loop, we create a new `Student` object using the constructor and assign it to the corresponding position in the array: `students[i] = Student(name, age);`.
 

4. After initializing all the objects, we use another loop to display each student's information by calling the `displayInfo()` member function.
 

5. Finally, we deallocate the memory used by the array of objects using the `delete[]` operator: `delete[] students;`. This ensures proper memory management and prevents memory leaks.

C++ example with malloc

In C++, you can also use the `malloc()` function to allocate memory for an array of objects dynamically. The `malloc()` function is a part of the C runtime library and is included in the `<cstdlib>` header.

For example: 

#include <iostream>
#include <cstdlib>
#include <cstring>
using namespace std;

class Student {
private:
    char name[50];
    int age;


public:
    Student(const char* n, int a) {
        strcpy(name, n);
        age = a;
    }


    void displayInfo() {
        cout << "Name: " << name << ", Age: " << age << endl;
    }
};


int main() {
    int size;
    cout << "Enter the number of students: ";
    cin >> size;


    Student* students = (Student*)malloc(size * sizeof(Student));


    char name[50];
    int age;
    for (int i = 0; i < size; i++) {
        cout << "Enter name and age for student " << i + 1 << ": ";
        cin >> name >> age;
        new (&students[i]) Student(name, age);
    }


    cout << "\nStudent Information:" << endl;
    for (int i = 0; i < size; i++) {
        students[i].displayInfo();
    }


    for (int i = 0; i < size; i++) {
        students[i].~Student();
    }
    free(students);


    return 0;
}
You can also try this code with Online C++ Compiler
Run Code

 

Output

Enter the number of students: 2
Enter name and age for student 1: Harsh 6
Enter name and age for student 2: Ria 23
Student Information:
Name: Harsh, Age: 6
Name: Ria, Age: 23


In this example:


1. We define a `Student` class with `name` and `age` attributes. The `name` attribute is a character array to demonstrate the usage of `malloc()`.


2. In the `main()` function, we dynamically allocate memory for an array of `Student` objects using `malloc()`: `Student* students = (Student*)malloc(size * sizeof(Student));`. The size of the memory block is calculated by multiplying the number of students (`size`) by the size of each `Student` object (`sizeof(Student)`).
 

3. We use a loop to input each student's name and age. Inside the loop, we use the placement new operator `new (&students[i]) Student(name, age);` to construct each `Student` object in the allocated memory block.
 

4. After initializing all the objects, we use another loop to display each student's information by calling the `displayInfo()` member function.
 

5. To properly deallocate the memory and destroy the objects, we use a loop to explicitly call the destructor for each `Student` object: `students[i].~Student();`.
 

6. Finally, we free the memory block using the `free()` function: `free(students);`.


Point to remember: It's important to note that using `malloc()` to allocate memory for objects requires manual memory management and explicit calls to constructors and destructors. In modern C++, it is generally recommended to use the `new` operator or smart pointers (`unique_ptr`, `shared_ptr`) for dynamic memory allocation of objects.

Advantages of Array of Objects

1. Efficient memory allocation: An array of objects allows you to allocate memory for multiple objects in a single block, which is more efficient than allocating memory for each object individually. This contiguous memory allocation improves cache locality & reduces memory fragmentation.
 

2. Simplified data management: By storing objects in an array, you can manage and manipulate related data more easily. You can access objects using their index, perform operations on multiple objects simultaneously, and iterate over the array using loops, making your code more concise and readable.
 

3. Code reusability & organization: Arrays of objects promote code reusability by allowing you to create and work with multiple instances of a class using a single data structure. This helps organize your code, reduce duplicated code, and make it easier to maintain and modify.
 

4. Efficient parameter passing: When you need to pass multiple objects to a function, using an array of objects is more efficient than passing individual objects. You can pass the array by reference or pointer, avoiding the overhead of copying each object separately.
 

5. Sorting and searching operations: Arrays of objects can be efficiently sorted and searched using various algorithms. You can apply sorting techniques like bubble sort, insertion sort, or quick sort directly to the array and perform binary search on sorted arrays to quickly find specific objects.
 

6. Dynamic sizing: By dynamically allocating arrays of objects using the `new` operator or `malloc()`, you can create arrays with sizes determined at runtime. This flexibility allows you to adapt the size of the array based on user input or other dynamic factors.
 

7. Compatibility with C-style arrays: Arrays of objects in C++ are compatible with C-style arrays, which means you can use them with existing C libraries or code that expects C-style arrays. This compatibility facilitates code integration & interoperability.

Disadvantages of Array of Objects

1. Fixed size: Arrays of objects have a fixed size that is determined at the time of declaration or allocation. Once the size is set, it cannot be changed dynamically. If you need to add or remove objects from the array, you have to create a new array with the desired size and copy the existing objects, which can be inefficient and time-consuming.

 

2. Lack of flexibility: Arrays of objects provide a rigid structure for storing objects. If you need to insert or delete objects in the middle of the array, you have to shift all the subsequent objects to maintain the contiguous memory layout. This can be costly in terms of time complexity, especially for large arrays.
 

3. Memory wastage: If you allocate an array of objects with a specific size and don't use all the elements, the unused memory is wasted. This can lead to inefficient memory utilization, especially if the array size is large and the number of actually used objects is small.
 

4. Difficulty in resizing: Resizing an array of objects is not an easy operation. You need to create a new array with the desired size, copy the existing objects to the new array, and then delete the old array. This process can be time-consuming and requires manual memory management, which can be error-prone.
 

5. Limited functionality: Arrays of objects provide basic functionality for accessing and manipulating objects, but they lack built-in methods for common operations like adding, removing, or searching for objects. You have to implement these operations manually, which can lead to more code complexity and potentially introduce bugs.
 

6. No built-in bounds checking: C++ arrays do not have built-in bounds checking. If you access an array element using an index that is out of bounds, it can lead to undefined behavior, crashes, or security vulnerabilities. It is the programmer's responsibility to ensure that array indices are within valid bounds.
 

7. Difficulty in maintaining order: If you need to maintain a specific order of objects in the array, like keeping the objects sorted, you have to manually implement the necessary operations like insertion, deletion, and sorting. This adds complexity to your code and may require additional data structures or algorithms.

Frequently Asked Questions

Can we have an array of objects with different data types?

No, an array of objects must contain objects of the same class or struct type. If you need to store objects of different types, you can use inheritance or pointers to base class objects.

How do you dynamically resize an array of objects?

To resize an array of objects, you need to create a new array with the desired size, copy the existing objects to the new array, and then delete the old array. This process involves manual memory management and can be inefficient for frequent resizing operations.

Can we pass an array of objects to a function?

Yes, you can pass an array of objects to a function either by value, reference, or pointer. Passing by reference or pointer is more efficient as it avoids copying the entire array.

Conclusion

In this article, we discussed arrays of objects in C++, which provide a way to store and manipulate multiple objects of the same class. We discussed its declaration, initialization, and examples using the new operator and malloc. Arrays of objects offer advantages like efficient memory allocation and simplified data management. However, they also have limitations like fixed size, lack of flexibility, and potential memory wastage. 

You can also check out our other blogs on Code360.

Live masterclass