Create an Array of Object


Like data member of the class we can also create an array of objects.
Array of object is useful when we want to create large number of objects of the same class.

Example:
#include<iostream.h>
class Student
{
int rollno;
char name[20];
public:
void Input();
void Output();
};
void Student::Input()
{
cout<<"Enter Roll Number:";
cin>>rollno;
cout<<"Enter Name:";
cin>>name;
}
void Student::Output()
{
cout<<"Roll Number:"<<rollno<<endl;
cout<<"Name:"<<name<<endl;
}
int main()
{
Student S[3];
int i;
for(i=0;i<3;i++)
S[i].Input();
for(i=0;i<3;i++)
S[i].Output();
return 0;
}

     

In above example we create an array of object using following statement: Student S [3]; Here, we create 3 objects. First object refer to S [0], second object refer to S[1] and third object refer to S[2].
Thus in array of object an object can be identified using the name of the array and index.
Output:
Enter Roll Number: 1
Enter Name: Mukesh
Enter Roll Number: 2
Enter Name: Ruchin
Enter Roll Number: 3
Enter Name: Mehul
RollNumber:1
Name: Mukesh
RollNumber:2
Name: Ruchin
RollNumber:3
Name: Mehul

Download Projects


Download Programs