Array of Objects in C++
Array of Objects in C++
Array of Objects in C++
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.
Syntax:
class_name array_name [size] ;
Example:
#include <iostream> MyClass obs[4];
class MyClass { int i;
int x; for(i=0; i < 4; i++)
public: obs[i].setX(i);
void setX(int i) { x = i; } for(i=0; i < 4; i++)
int getX() { return x; } cout << "obs[" << i << "].getX(): " <<
}; obs[i].getX() << "\n";
void main() getch();
{ }
Suppose we have 50 students in a class and we have to input the name and marks of all the 50 students.
Then creating 50 different objects and then inputting the name and marks of all those 50 students is not
a good option. In that case, we will create an array of objects as we do in case of other data-types.
Let's see an example of taking the input of name and marks of 5 students by creating an array of the
objects of students.
#include <iostream> cin >> marks;
#include <string> }
void displayInfo()
using namespace std; {
class Student cout << "Name : " << name << endl;
{ cout << "Marks : " << marks << endl;
string name; }
int marks; };
public:
void getName()
{
getline( cin, name );
}
void getMarks()
{
int main()
{
Student st[5];
for( int i=0; i<5; i++ )
{
cout << "Student " << i + 1 <<
endl;
cout << "Enter name" << endl;
st[i].getName();
cout << "Enter marks" << endl;
st[i].getMarks();
}