In this C++ tutorial, you will learn how to declare and initialize an array of objects. We shall discuss two ways in which we create an array of objects, with examples.
C Array of Objects
You can store objects of user defined datatype in a C++ Array.
To store objects of user defined datatype in an array, you can declare an array of the specific type and initialize the array just like an array of ints.
1 Array of Objects Declare and Initialize Separately
In the following example, we shall declare an array of type Student, with size of five. Student is a class that we defined in the program. Then we shall assign objects using index of array.
C++ Program
#include <iostream> using namespace std; class Student { public: string name; int rollno; Student() {} Student(string x, int y) { name = x; rollno = y; } void printDetails() { cout << rollno << " - " << name << endl; } }; int main() { //declare array with specific size Student students[5]; //assign objects students[0] = Student("Ram", 5); students[1] = Student("Alex", 1); students[2] = Student("Lesha", 4); students[3] = Student("Emily", 3); students[4] = Student("Anita", 2); for(int i=0; i < 5; i++) { students[i].printDetails(); } }
Output
5 - Ram 1 - Alex 4 - Lesha 3 - Emily 2 - Anita
2 Array of Objects Declare and Initialize in a Single Line
In the following example, we shall declare an array of type Student, and initialize the array with objects of Student type in a single line.
C++ Program
#include <iostream> using namespace std; class Student { public: string name; int rollno; Student() {} Student(string x, int y) { name = x; rollno = y; } void printDetails() { cout << rollno << " - " << name << endl; } }; int main() { //declare array with specific size Student students[] = {Student("Ram", 5), Student("Lesha", 4), Student("Anita", 2)}; for(int i=0; i < 3; i++) { students[i].printDetails(); } }
Output
5 - Ram 4 - Lesha 2 - Anita
Conclusion
In this C++ Tutorial, we learned how to initialize an array of custom class type objects, with example C++ programs.