OOP

Arrays as class data member

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:

Why Use Arrays as Class Member Data?

Syntax:

class MyClass {
private:
  int myArray[size]; // Array as member data (size can be fixed or dynamic)
  // ... other members
public:
  // ... member functions
};

Considerations:

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
};

Key Points: