The Wayback Machine - https://web.archive.org/web/20240706074921/https://www.geeksforgeeks.org/array-of-objects-in-c-with-examples/
Open In App

Array of Objects in C++ with Examples

Last Updated : 01 Jul, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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 C/C++ can store derived data types such as structures, pointers, etc. Given below is the picture representation of an array.

Example:
Let’s consider an example of taking random integers from the user.

Array allocation

Array


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];

The Array of Objects stores objects. An array of a class type is also known as an array of objects.

Example#1: 
Storing more than one Employee data. Let’s assume there is an array of objects for storing employee data emp[50].

Array of objects

Below is the C++ program for storing data of one Employee:

C++
// C++ program to implement 
// the above approach
#include<iostream>
using namespace std;

class Employee
{
  int id;
  char name[30];
  public:
  void getdata();//Declaration of function
  void putdata();//Declaration of function
};
void Employee::getdata(){//Defining of function
  cout<<"Enter Id : ";
  cin>>id;
  cout<<"Enter Name : ";
  cin>>name;
}
void Employee::putdata(){//Defining of function
  cout<<id<<" ";
  cout<<name<<" ";
  cout<<endl;
}
int main(){
  Employee emp; //One member 
  emp.getdata();//Accessing the function
  emp.putdata();//Accessing the function
  return 0;

}


Let’s understand the above example –

  • In the above example, a class named Employee with id and name is being considered.
  • The two functions are declared-
    • getdata(): Taking user input for id and name.
    • putdata(): Showing the data on the console screen.

This program can take the data of only one Employee. What if there is a requirement to add data of more than one Employee. Here comes the answer Array of Objects. An array of objects can be used if there is a need to store data of more than one employee. Below is the C++ program to implement the above approach-

C++
// C++ program to implement 
// the above approach
#include<iostream>
using namespace std;

class Employee
{
  int id;
  char name[30];
  public:
  
  // Declaration of function
  void getdata();
  
  // Declaration of function
  void putdata();
};

// Defining the function outside 
// the class
void Employee::getdata()
{ 
  cout << "Enter Id : ";
  cin >> id;
  cout << "Enter Name : ";
  cin >> name;
}

// Defining the function outside 
// the class
void Employee::putdata()
{
  cout << id << " ";
  cout << name << " ";
  cout << endl;
}

// Driver code
int main()
{
  // This is an array of objects having
  // maximum limit of 30 Employees
  Employee emp[30]; 
  int n, i;
  cout << "Enter Number of Employees - ";
  cin >> n;
  
  // Accessing the function
  for(i = 0; i < n; i++) 
    emp[i].getdata();
  
  cout << "Employee Data - " << endl;
  
  // Accessing the function
  for(i = 0; i < n; i++) 
    emp[i].putdata();
}


Output:


Explanation:
In this example, more than one Employee’s details with an Employee id and name can be stored.

  • Employee emp[30] – This is an array of objects having a maximum limit of 30 Employees.
  • Two for loops are being used-
    • First one to take the input from user by calling emp[i].getdata() function.
    • Second one to print the data of Employee by calling the function emp[i].putdata() function.

Example#2: 

C++
// C++ program to implement
// the above approach
#include<iostream>
using namespace std;
class item
{
  char name[30];
  int price;
  public:
  void getitem();
  void printitem();
};
 
// Function to get item details
void item::getitem()
{
  cout << "Item Name = ";
  cin >> name;
  cout << "Price = ";
  cin >> price;    
}

// Function to print item
// details
void item ::printitem()
{
  cout << "Name : " << name << 
          "\n";
  cout << "Price : " << price << 
          "\n";
}

const int size = 3;

// Driver code
int main()
{
  item t[size];
  for(int i = 0; i < size; i++)
  {
    cout << "Item  : " << 
            (i + 1) << "\n";
    t[i].getitem();
  }
  
  for(int i = 0; i < size; i++)
  {
    cout << "Item Details : " << 
             (i + 1) << "\n";
    t[i].printitem();
  }
}


Output:

Output#2

Advantages of Array of Objects: 

  1. The array of objects represent storing multiple objects in a single name.
  2. In an array of objects, the data can be accessed randomly by using the index number.
  3. Reduce the time and memory by storing the data in a single variable.

Disadvantages of Array of Objects:

  1. The main disadvantage with arrays of objects is that the constructor runs for each object. If the default constructor doesn’t do the right thing for multiple objects in the array, we have to specify the constructor arguments for each element at the time the array is declared, which we wouldn’t have to do if we allocated an array of object pointers, and allocated objects as needed.
C++
// C++ program to implement
// the above approach
#include <iostream>
using namespace std;

class Employee {
    int id;
    char name[30];

public:
    Employee() { cout << "Constructor Run\n"; }
    void getdata(); // Declaration of function
    void putdata(); // Declaration of function
};
void Employee::getdata()
{ // Defining of function
    cout << "Enter Id : ";
    cin >> id;
    cout << "Enter Name : ";
    cin >> name;
}
void Employee::putdata()
{ // Defining of function
    cout << id << " ";
    cout << name << " ";
    cout << endl;
}
int main()
{
    Employee emp[5]; // One member
    return 0;
}

Output
Constructor Run
Constructor Run
Constructor Run
Constructor Run
Constructor Run


Similar Reads

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
How to initialize Array of objects with parameterized constructors in C++
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:
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
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
Count the number of objects using Static member function
Prerequisite : Static variables , Static Functions Write a program to design a class having static member function named showcount() which has the property of displaying the number of objects created of the class. Explanation: In this program we are simply explaining the approach of static member function. We can define class members and member fun
2 min read
Introduction to Complex Objects and Composition
An object is a basic unit of Object-Oriented Programming and represents the real-life entities. Complex objects are the objects that are built from smaller or a collection of objects. For example, a mobile phone is made up of various objects like a camera, battery, screen, sensors, etc. In this article, we will understand the use and implementation
4 min read
Anonymous Objects in C++
Prerequisite: Class and Objects in C++ An Object is an instance of a Class. A class has no memory allocated it is just like a blueprint, but when it is instantiated (i.e. an object is created) memory is allocated just like the real-world instance of that blueprint. An object that does not have a reference variable is known as an anonymous object. T
4 min read
Creating a Vector of Class Objects in C++
Prerequisites: Object Oriented Programming in C++Vector in C++ Class is a user-defined data type that can be accessed by creating objects or instances of that class. A vector is a type of container which can store elements of a similar type. Vector of Class The vector of class objects is an example of a custom vector made where we can store multipl
3 min read
Reference to Dynamic Objects in C++
In C++, the objects can be created at run-time. C++ supports two operators new and delete to perform memory allocation and de-allocation. These types of objects are called dynamic objects. The new operator is used to create objects dynamically and the delete operator is used to delete objects dynamically. The dynamic objects can be created with the
3 min read
How to make a C++ class whose objects can only be dynamically allocated?
The problem is to create a class such that the non-dynamic allocation of object causes compiler error. For example, create a class 'Test' with following rules. C/C++ Code Test t1; // Should generate compiler error Test *t3 = new Test; // Should work fine The idea is to create a private destructor in the class. When we make a private destructor, the
2 min read
Practice Tags :
three90RightbarBannerImg