So this is the original code:
class IntegerArray {
public:
int *data;
int size;
};
int main() {
IntegerArray arr;
arr.size = 2;
arr.data = new int[arr.size];
arr.data[0] = 4; arr.data[1] = 5;
delete[] a.data;
}
After moving arr.data = new int[arr.size]
to a constructor, it becomes
class IntegerArray {
public:
int *data;
int size;
IntegerArray(int size) {
data = new int[size];
this->size = size;
}
};
int main() {
IntegerArray arr(2);
arr.data[0] = 4; arr.data[1] = 5;
delete[] arr.data;
}
I'm fairly lost on what the code is trying to do. For
IntegerArray(int size) {
data = new int[size];
this->size = size;
}
Is int size just the same as the int size that was declared in the class IntegerArray?
Does data = new int[size]
just tell us that data is pointing to the output of the array at int size, with new saying that the size of the array is variable?
Is this-> size = size
just a pointer that tells us that the size value of the constructor is just equal to the size parameter of the class?
Why are arr.data[0]
and arr.data[1]
even mentioned after IntegerArray arr(2)? They don't seem to follow the constructor, but I'm probably just too tired to comprehend that part.