Arrays can be used as member data in C++ classes to manage collections of elements that belong to an object. Here’s a breakdown of the concept:
Point
class might have an array to store coordinates (x, y), or a Student
class could have an array to store exam scores.Syntax:
class MyClass {
private:
int myArray[size]; // Array as member data (size can be fixed or dynamic)
// ... other members
public:
// ... member functions
};
new
) to create an array with a size determined at runtime.vector
or array
for more flexibility and features like automatic resizing.Example (Fixed Size Array):
class Point {
private:
int coordinates[2]; // Array to store x and y coordinates
public:
Point(int x, int y) {
coordinates[0] = x;
coordinates[1] = y;
}
int GetX() const { return coordinates[0]; }
int GetY() const { return coordinates[1]; }
// ... other member functions
};
Example (Dynamic Array):
class Student {
private:
int* scores; // Pointer to an array of scores (dynamically allocated)
int size; // Size of the scores array
public:
Student(int numCourses) {
size = numCourses;
scores = new int[size]; // Allocate memory for scores
}
~Student() {
delete[] scores; // Deallocate memory in destructor
}
void SetScore(int index, int score) {
if (index >= 0 && index < size) {
scores[index] = score;
}
}
// ... other member functions
};