Like array of other user-defined data types, an array of type class can also be created. The array of type class contains the objects of the class as its individual elements. Thus, an array of a class type is also known as an array of objects. An array of objects is declared in the same way as an array of any built-in data type.
The syntax for declaring an array of objects is
class_name array_name [size] ;
To understand the concept of an array of objects, consider this example.
Example : A program to demonstrate the concept of array of objects
#include<iostream>
using namespace std;
class books
{
char tit1e [30];
float price ;
public:
void getdata ();
void putdata ();
} ;
void books :: getdata ()
{
cout<<"Title:”;
Cin>>title;
cout<<"Price:”;
cin>>price;
}
void books :: putdata ()
{
cout<<"Title:"<<title<< "\n";
cout<<"Price:"<<price<< "\n”;
const int size=3 ;
int main ()
{
books book[size] ;
for(int i=0;i<size;i++)
{
cout<<"Enter details o£ book "<<(i+1)<<"\n";
book[i].getdata();
}
for(int i=0;i<size;i++)
{
cout<<"\nBook "<<(i+l)<<"\n";
book[i].putdata() ;
}
return 0;
}
The output of the program is
Enter details of book 1
Title: c++
Price: 325
Enter details of book 2
Price:. 455
Enter details of book 3
Title: Java
Price: 255
Book 1
Title: c++
Price: 325
Book 2
Title: DBMS
Price: 455
Book 3
Title: Java
Price: 255
In this example, an array book of the type class books and size three is declared. This implies that book is an array of three objects of the class books. Note that every object in the array book can access public members of the class in the same way as any other object, that is, by using the dot operator.]. However, member functions are stored at a different place in memory and shared among all the array members. For instance, the memory space is allocated to the the array of objects book of the class