Arrays of objects
Arrays of objects
The array of structure in C++ and an array of the object are both the same.
In the array of object in C++, each element of an array becomes an object (same class’s), which means the
array of object in c++ is a collection of objects of the same class. Just as an object is a collection of data-
members and function-members. so each element of an array is a collection of data-member and function-
member.
The array of object is important as if you want to store 10 student record, then you do not need to declare
10 objects for each student. You can make the class object an array of an element.
In an array of object, make the object an array type variable. And because every element of the array will
now be an object, these objects are accessed with index value just like a simple array. In this, the object
name will be the same but due to the index value being different, the object will also be different.
Example 1
#include <iostream>
struct stud
public:
int rno;
void getroll()
cout<<"\nEnter roll:";
cin>>rno;
void printroll()
{
cout<<"\nroll:";
cout<<rno;
};
int main()
stud s[5];
for(int i=0;i<5;i++)
s[i].getroll();
s[2].printroll();
return 0;
Example 2
and we know that object is a collection of data member and function member so,
Here we have created an object by declaring an array of sizes. The greater the size of the array, the more
objects will be created. Creating an object means that how many students he wants to store the record
#include<iostream>
#include<stdio>
class student
int roll_no;
char name[20];
void get_record(void);
void show_record(void);
};
cin>>roll_no;
gets(name);
}
void student::show_record() // display record
cout<<"\nName : "<<name;
obj[i].get_record();
obj[j].show_record();
return 0;
we can also use the following code instead of a loop, but its only fine for 1-2 statements. such as,
student obj[2];
Whereas we have to use the loop when the statement is incremented. You can understand the above
program with the help of the following diagram –
OUTPUT:-
Roll no: 11
Roll no: 12
Explanation:-
as two object (obj[0], obj[1]) will be created in this program. Which will store two student records-
First object obj[0] first student and another object obj[1] is storing another student record.
Here is the diagram below, that show how the records of these two students have been stored in the
program-
If you want, you can store 10 students record instead of two by increasing the array of size, Remember
here, the object name is the same (obj), but due to the index value ([value]) being different, they become
different.