Array of objects in C++

What is an Array of Objects in C++?

Explanation

Arrays of variables of type "class" is known as "Array of objects". The "identifier" used to refer the array of objects is an user defined data type.

Example :



#include <iostream.h>
const int MAX =100;
class Details
{
private:
int salary;
float roll;
public:
void getname( )
{
cout << "\n Enter the Salary:";
cin >> salary;
cout << "\n Enter the roll:";
cin >> roll;
}
void putname( )
{
cout << "Employees" << salary <<
"and roll is" << roll << '\n';
}
};
void main()
{
Details det[MAX];
int n=0;
char ans;
do{
cout << "Enter the Employee Number::" << n+1;
det[n++].getname;
cout << "Enter another (y/n)?: " ;
cin >> ans;
} while ( ans != 'n' );
for (int j=0; j<n; j++)
{
cout << "\nEmployee Number is:: " << j+1;
det[j].putname( );
}
}

Result :

Enter the Employee Number:: 1
Enter the Salary:20
Enter the roll:30
Enter another (y/n)?: y
Enter the Employee Number:: 2
Enter the Salary:20
Enter the roll:30
Enter another (y/n)?: n

In the above example an array of object "det" is defined using the user defined data type "Details". The class element "getname()" is used to get the input that is stored in this array of objects and putname() is used to display the information.

C++ Tutorial


Ask Questions

Ask Question