Summary: In this programming example, we will learn to create an array of objects in C++.
An array of objects is similar to the array of primitive data types such as int
, double
, char
, etc.
The syntax to create an array of any user defined objects is:
1 | <class> <array_name>[SIZE]; |
We define an array of class type and initialize it with the objects as values.
Here’s a C++ example where we create an array of objects in two different ways:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | #include <iostream> using namespace std; class Language{ public: string name; //Default constructor Language(){} //Parameterized constructor Language(string name){ this->name = name; } }; //To display the objects void display(Language arr[],int length){ for(int i=0; i<length; i++){ cout << arr[i].name << endl; } } int main(){ //1. First way: Initializeobject at the time of declaration Language object_array[] = {Language("C"), Language("C++"), Language("Java")}; display(object_array, 3); cout << endl << "-------------------------------" << endl; //2. Second way: First define, then initialize with objects Language object_array_2[3]; object_array_2[0] = Language("C"); object_array_2[1] = Language("C++"); object_array_2[2] = Language("Java"); display(object_array_2, 3); return 0; } |
Output:

An Array of Pointer Objects in C++
An object pointer is a pointer that stores the address location of an instance of the class.
Similar to normal objects, multiple object pointers can be stored in a single array.
Recommend: If you don’t know what the new operator is?
Here is a C++ example, which creates an array of pointers in two ways:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | #include <iostream> using namespace std; class Language{ public: string name; Language(){} Language(string name){ this->name = name; } }; //To display the pointer objects void display(Language *arr[],int length){ for(int i=0; i<length; i++){ cout << arr[i]->name << endl; } } int main(){ //1. First Way: Initialize array at the time of declaration Language *array[] = {new Language("C"), new Language("C++"), new Language("Java")}; display(array, 3); cout << endl << "-------------------------------" << endl; //2. Second Way: First define array, then do the initialization Language *array_2[3]; array_2[0] = new Language("C"); array_2[1] = new Language("C++"); array_2[2] = new Language("Java"); display(array_2, 3); return 0; } |
Output:

In this tutorial, we learned how to create an array of user-defined objects in the C++ programming language.