C++ arrays of objects
We know that an array can be any data type including struct. similar we can also have arrays of variables that are of the types class. such variable are called array of objects
consider the following class definition
The identifier employee is user defined data type and can be used to create objects that related to different categories of the employee Example
class student
{
name[20];
marks;
getdata();
putdata();
};
|
student school[4];
student graduate[8];
student postgraduate[15];
|
The array school contains four objects, namely, school[0],school[1],school[2],school[3] of type student class.
similarly the graduate array contains 8 objects and postpraduate array contains 15 objects.
since an array of objects behaves like any other array, we can use the usual array accessing method to access individual elements, and then the dot member operator to access the member functions.
for example The statement school[i].putdata();
|
will display the data of the ith position element of the array manager. That is this statement requests the object school[i] to invoke the member function putdata()
An array of objects is stored inside the memory in the same way as multi dimensional array. The array school is represented in below figure.
Note that only the space for data items of the objects is created . Member functions are stored separately and will be used by all the objects
<iostream>
using namespace std;
class student
{
name[20];
marks;
:
getdata();
putdata();
};
student:: getdata()
{
std::cout <<"Enter name:";
std::cin >>name;
std::cout <<"Enter Marks:";
std::cin >>marks;
}
student::putdata()
{
std::cout <<"Name:"<<name<<"\n";
std::cout <<"marks:"<<marks<<"\n";
}
size=3;
main()
{
int i;
student school[size];
( i=0;i<size;i++)
{
std::cout<<"\n Details of school"<<i+1<<"\n";
school[i].getdata();
}
std::cout<<"\n";
(i=0;i < size;i++)
{
std::cout <<"\n school"<<i+1 <<"\n";
school[i].putdata();
}
}
|
Input:
Details of school 1
Enter name:nitish
Enter Marks:56
Details of school2
Enter name:Gaurav
Enter Marks:78
Details of school3
Enter name:chetan
Enter Marks:99
|
program output
school1
Name:nitish
Marks:56
school2
Name:gaurav
Marks:78
school3
Name:chetan
Marks:99
|