/*Write your own integer array class named IntArray from scratch (do not use
* std::array or std::vector). Users should pass in the size of the array when
* it is created, and the array should be dynamically allocated.*/
#include <iostream>
usingnamespace std;
class IntArray {
private:
int* arr0{0};
size_t length;
public:
IntArray(const size_t n) : length{n} { arr0 = newint[n]; }
// overload subscript op
int& operator[](const size_t element) const { returnthis->arr0[element]; }
// IntArray1 = IntArray2
// deep copy
IntArray& operator=(IntArray& given_arr) {
this->length = given_arr.length;
this->arr0 = given_arr.arr0;
for (size_t i = 0; i < length; ++i) {
this->arr0[i] = given_arr[i];
}
return *this;
}
friend ostream& operator<<(ostream& os, const IntArray& arr) {
for (size_t i = 0; i < arr.length; ++i) {
os << arr[i] << " ";
}
return os;
}
// deleting arr0 will make the program crash!
//~IntArray() { delete[] arr0; }
};
// a function that just returns an IntArray
IntArray fillArray() {
IntArray a(5);
a[0] = 5;
a[1] = 8;
a[2] = 2;
a[3] = 3;
a[4] = 6;
return a;
}
int main() {
IntArray a = fillArray();
std::cout << a << '\n';
IntArray b(1);
a = a;
b = a; // copy
std::cout << b << '\n';
return 0;
}
Yes and No.
All class member variables are destroyed when the object is destroyed, but any dynamic memory allocated for them is NOT.
so
class leak
{
int * ip;
leak::leak(){ip = new int[1000];} //leaks. ip is destroyed when an object dies, but the memory allocated is still owned by the program. you need a delete[] ip; in the dtor.
}
thankfully vectors destroy their own memory, so using that instead of a pointer in your class solves the problem (not here, but in unlimited code, here you were told not to use a vector).