C++ program to create array of objects by taking user inputs

Introduction :

In this tutorial, we will learn how to create an array of objects in C++ by taking the inputs from the user. We will create one Student class that can hold the name and age of a Student. We will create one array of Student class that will hold different Student objects. The array elements will be filled by the user. The program will ask the user to enter student name and age one by one and insert that data to the array.

Example program :

Below is the example C++ program :

#include <iostream>

using namespace std;

class Student
{
public:
    string name;
    int age;

    void readDetails()
    {
        cout << "Enter name : ";
        getline(cin, name);

        cout << "Enter age :" << endl;
        cin >> age;
        fflush(stdin);
    }

    void printDetails()
    {
        cout << "Name : " << name << " Age : " << age << endl;
    }
};

int main()
{
    Student studentArray[4];

    for (int i = 0; i < 4; i++)
    {
        cout << "Enter details for student " << (i + 1) << endl;
        studentArray[i].readDetails();
    }

    cout << "You have entered : " << endl;
    for (int i = 0; i < 4; i++)
    {
        studentArray[i].printDetails();
    }

    return 0;
}

Here,

  • Student class is used to hold the details of a Student : name and age.
  • readDetails method reads the details of a Student from the user input.
  • printDetails method prints out the details of a Student.
  • studentArray is an array of Student objects of size 4. Using one for loop, we are reading the details of students using readDetails method.
  • Once the reading is completed, we are printing out the details again using another for loop.

Below is the output of this example :

Enter details for student 1
Enter name : Alex
Enter age :
20
Enter details for student 2
Enter name : Sarah
Enter age :
19
Enter details for student 3
Enter name : Rachel
Enter age :
20
Enter details for student 4
Enter name : Bob
Enter age :
21
You have entered : 
Name : Alex Age : 20
Name : Sarah Age : 19
Name : Rachel Age : 20
Name : Bob Age : 21