Array of Objects in C++

We know that an array can be of any data type. Hence, we can also have arrays of variables that are of the type class. Such variables are called array of objects.

Consider the following class definition:

class employee
          char name[30];
          float age;
          void getdata();
          void putdata();

The identifier employee is a user-defined data type and can be used to create objects that relate to different categories of the employee.

For example, consider the following:

employee managers[3]; //array of manager
employee foremen[15]; //array of foreman
employee workers[75]; //array of worker

In above declaration, the array managers contains three objects (managers), namely, managers[0], managers[1] and managers[2], of the type employee class.

Similarly, the foremen array contains 15 objects (foremen) and the workers array contains 75 objects (workers).

Since, an array of objects behave like any other array, we can use the usual array-accessing methods to access individual elements and then the dot member operator to access the member functions.

For example, the statement:

will display the data of the ith element of the array managers. That is, this statement requests the object manager[i] to invoke the member function putdata().

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *