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:
<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:
#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:
#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.