In C++, arrays are fundamental data structures that allow you to store multiple elements of the same type sequentially in memory. When dealing with arrays of objects of a class, you might need to traverse through them for various purposes such as manipulation, searching, or printing. Using pointers provides an efficient and flexible way to iterate over these arrays. In this article, we’ll explore how to traverse an array of objects of a class using pointers in C++, accompanied by an example program and a detailed line-by-line explanation.
Understanding Array of Objects and Pointers
Before diving into traversing arrays of objects using pointers, let’s briefly review what arrays of objects and pointers are in C++.
An array of objects is simply a collection of objects of a class stored in contiguous memory locations. Each element of the array represents an instance of the class.
Pointers in C++ are variables that store memory addresses. They are powerful tools that enable dynamic memory allocation, efficient data manipulation, and indirect access to variables and functions.
Example Program: Traversing an Array of Objects
Suppose we have a class called Student
representing student records with attributes such as name
and rollNumber
. We want to create an array of Student
objects and traverse through it using pointers.
#include <iostream>
#include <string>
class Student {
public:
std::string name;
int rollNumber;
Student(std::string name, int rollNumber) : name(name), rollNumber(rollNumber) {}
};
int main() {
const int arraySize = 3;
Student students[arraySize] = { {"Alice", 101}, {"Bob", 102}, {"Charlie", 103} };
// Pointer to traverse the array
Student *ptr = students;
// Traversing the array using pointer
for (int i = 0; i < arraySize; ++i) {
std::cout << "Name: " << (ptr + i)->name << ", Roll Number: " << (ptr + i)->rollNumber << std::endl;
}
return 0;
}
Explanation
- We define a class
Student
with two member variables:name
androllNumber
. In the constructor, we initialize these variables. - In the
main()
function, we declare an arraystudents
ofStudent
objects with a size ofarraySize
, which is set to 3. We initialize the array with threeStudent
objects using uniform initialization. - We declare a pointer
ptr
of typeStudent
and initialize it with the address of the first element of thestudents
array. Since the name of an array decays to a pointer to its first element,ptr
now points to the firstStudent
object in the array. - We traverse through the array using a
for
loop. Inside the loop, we use pointer arithmetic to access eachStudent
object.(ptr + i)
calculates the memory address of thei
-th element relative to the base address pointed byptr
, and->
is used to access the member variablesname
androllNumber
of eachStudent
object. - We print the name and roll number of each student using the pointer-based access.
Here are few more examples of traversing objects of class using pointers
This program demonstrates how to traverse an array of objects of a class using pointers and display the values of each object.
#include <iostream>
class MyClass {
public:
MyClass(int val) : value(val) {}
void display() {
std::cout << "Value: " << value << std::endl;
}
private:
int value;
};
int main() {
const int size = 3;
MyClass objArray[size] = {MyClass(10), MyClass(20), MyClass(30)};
MyClass *ptr = objArray; // Pointer to the first object in the array
for (int i = 0; i < size; ++i) {
ptr->display(); // Display value of current object
ptr++; // Move pointer to the next object in the array
}
return 0;
}
Explanation:
class MyClass { ... };
: Defines a classMyClass
with a member variablevalue
and a member functiondisplay
.MyClass objArray[size] = {MyClass(10), MyClass(20), MyClass(30)};
: Declares an array ofMyClass
objects and initializes them with specific values.MyClass *ptr = objArray;
: Declares a pointerptr
and assigns it to the address of the first object in the array.for (int i = 0; i < size; ++i) { ptr->display(); ptr++; }
: Iterates through each object in the array using the pointerptr
, displaying the value of each object and then moving the pointer to the next object.
The program above demonstrates how to traverse an array of objects of a class using pointers and display the values of each object.
Traversing Array of Objects of a Class Using Pointers – Calculate Total
Introduction: This program demonstrates how to traverse an array of objects of a class using pointers and calculate the total of a member variable of each object.
#include <iostream>
class MyClass {
public:
MyClass(int val) : value(val) {}
int getValue() const {
return value;
}
private:
int value;
};
int main() {
const int size = 3;
MyClass objArray[size] = {MyClass(10), MyClass(20), MyClass(30)};
MyClass *ptr = objArray; // Pointer to the first object in the array
int total = 0;
for (int i = 0; i < size; ++i) {
total += ptr->getValue(); // Add value of current object to total
ptr++; // Move pointer to the next object in the array
}
std::cout << "Total: " << total << std::endl;
return 0;
}
Explanation:
class MyClass { ... };
: Defines a classMyClass
with a member variablevalue
and a member functiongetValue
.MyClass objArray[size] = {MyClass(10), MyClass(20), MyClass(30)};
: Declares an array ofMyClass
objects and initializes them with specific values.MyClass *ptr = objArray;
: Declares a pointerptr
and assigns it to the address of the first object in the array.int total = 0;
: Initializes a variabletotal
to store the sum of the values.for (int i = 0; i < size; ++i) { total += ptr->getValue(); ptr++; }
: Iterates through each object in the array using the pointerptr
, adding the value of each object to thetotal
variable and then moving the pointer to the next object.std::cout << "Total: " << total << std::endl;
: Prints the total value.
The program above demonstrates how to traverse an array of objects of a class using pointers and calculate the total of a member variable of each object.
Traversing Array of Objects of a Class Using Pointers – Find Maximum Value
Introduction: This program demonstrates how to traverse an array of objects of a class using pointers and find the maximum value of a member variable among the objects.
#include <iostream>
class MyClass {
public:
MyClass(int val) : value(val) {}
int getValue() const {
return value;
}
private:
int value;
};
int main() {
const int size = 5;
MyClass objArray[size] = {MyClass(30), MyClass(10), MyClass(50), MyClass(20), MyClass(40)};
MyClass *ptr = objArray; // Pointer to the first object in the array
int max = ptr->getValue(); // Initialize max with the value of the first object
for (int i = 1; i < size; ++i) {
ptr++; // Move pointer to the next object in the array
if (ptr->getValue() > max) {
max = ptr->getValue(); // Update max if current object's value is greater
}
}
std::cout << "Maximum Value: " << max << std::endl;
return 0;
}
Explanation:
class MyClass { ... };
: Defines a classMyClass
with a member variablevalue
and a member functiongetValue
.MyClass objArray[size] = { ... };
: Declares an array ofMyClass
objects and initializes them with specific values.MyClass *ptr = objArray;
: Declares a pointerptr
and assigns it to the address of the first object in the array.int max = ptr->getValue();
: Initializes a variablemax
with the value of the first object.for (int i = 1; i < size; ++i) { ... }
: Iterates through each object in the array using the pointerptr
, starting from the second object.ptr++;
: Moves the pointer to the next object in the array.if (ptr->getValue() > max) { max = ptr->getValue(); }
: Checks if the value of the current object is greater than the current maximum valuemax
and updatesmax
if necessary.
std::cout << "Maximum Value: " << max << std::endl;
: Prints the maximum value found.
The program above demonstrates how to traverse an array of objects of a class using pointers and find the maximum value of a member variable among the objects.
Traversing Array of Objects of a Class Using Pointers – Update Values
Introduction: This program demonstrates how to traverse an array of objects of a class using pointers and update the values of each object.
#include <iostream>
class MyClass {
public:
MyClass(int val) : value(val) {}
void setValue(int val) {
value = val;
}
int getValue() const {
return value;
}
private:
int value;
};
int main() {
const int size = 3;
MyClass objArray[size] = {MyClass(10), MyClass(20), MyClass(30)};
MyClass *ptr = objArray; // Pointer to the first object in the array
for (int i = 0; i < size; ++i) {
ptr->setValue(ptr->getValue() * 2); // Double the value of current object
ptr++; // Move pointer to the next object in the array
}
// Display updated values
ptr = objArray; // Reset pointer to the first object
for (int i = 0; i < size; ++i) {
std::cout << "Value of Object " << i + 1 << ": " << ptr->getValue() << std::endl;
ptr++; // Move pointer to the next object in the array
}
return 0;
}
Explanation:
class MyClass { ... };
: Defines a classMyClass
with a member variablevalue
and member functionssetValue
andgetValue
.MyClass objArray[size] = { ... };
: Declares an array ofMyClass
objects and initializes them with specific values.MyClass *ptr = objArray;
: Declares a pointerptr
and assigns it to the address of the first object in the array.for (int i = 0; i < size; ++i) { ptr->setValue(ptr->getValue() * 2); ptr++; }
: Iterates through each object in the array using the pointerptr
, doubling the value of each object and then moving the pointer to the next object.- Resetting and traversing the array again to display the updated values:
ptr = objArray;
: Resets the pointerptr
to the address of the first object in the array.for (int i = 0; i < size; ++i) { ... }
: Iterates through each object in the array using the pointerptr
, displaying the updated value of each object, and then moving the pointer to the next object.
The program above demonstrates how to traverse an array of objects of a class using pointers and update the values of each object.
Traversing Array of Objects of a Class Using Pointers – Custom Operation
Introduction: This program demonstrates how to traverse an array of objects of a class using pointers and perform a custom operation on each object.
#include <iostream>
class MyClass {
public:
MyClass(int val) : value(val) {}
void customOperation() {
value *= 2; // Double the value
}
int getValue() const {
return value;
}
private:
int value;
};
int main() {
const int size = 4;
MyClass objArray[size] = {MyClass(2), MyClass(4), MyClass(6), MyClass(8)};
MyClass *ptr = objArray; // Pointer to the first object in the array
// Perform custom operation on each object using pointers
for (int i = 0; i < size; ++i) {
ptr->customOperation(); // Perform custom operation on current object
ptr++; // Move pointer to the next object in the array
}
// Display updated values
ptr = objArray; // Reset pointer to the first object
for (int i = 0; i < size; ++i) {
std::cout << "Value of Object " << i + 1 << ": " << ptr->getValue() << std::endl;
ptr++; // Move pointer to the next object in the array
}
return 0;
}
Explanation:
class MyClass { ... };
: Defines a classMyClass
with a member variablevalue
, a member functioncustomOperation
, and a member functiongetValue
.MyClass objArray[size] = { ... };
: Declares an array ofMyClass
objects and initializes them with specific values.MyClass *ptr = objArray;
: Declares a pointerptr
and assigns it to the address of the first object in the array.for (int i = 0; i < size; ++i) { ptr->customOperation(); ptr++; }
: Iterates through each object in the array using the pointerptr
, performing a custom operation on each object, and then moving the pointer to the next object.- Resetting and traversing the array again to display the updated values:
ptr = objArray;
: Resets the pointerptr
to the address of the first object in the array.for (int i = 0; i < size; ++i) { ... }
: Iterates through each object in the array using the pointerptr
, displaying the updated value of each object, and then moving the pointer to the next object.
The program above demonstrates how to traverse an array of objects of a class using pointers and perform a custom operation on each object.
The examples above illustrate various ways of traversing arrays of objects of a class using pointers in C++.
Conclusion
Traversing an array of objects of a class using pointers in C++ provides a flexible and efficient way to iterate through the elements of the array. By understanding how pointers work with arrays and classes, you can effectively manipulate and process data stored in arrays of objects, enabling you to perform various operations with ease.