I have a class called Dynamic Array which holds the elements of some generic object, T
. I want to create a storehouse where I will hold medicine, and for this I want to use that dynamic array as the representation of the storehouse. This is my dynamic array's constructor and destructor (I have other methods for it, but they are not relevant for this question):
class DynamicArray {
private:
int capacity, size;
T* elements;
public:
DynamicArray();
~DynamicArray();
};
DynamicArray::DynamicArray() {
this->size = 0;
this->capacity = INITIAL_CAPACITY;
this->elements = new TElem[INITIAL_CAPACITY];
}
DynamicArray::~DynamicArray() {
delete[] this->elements;
}
Now I want to create the storehouse. This is what I tried:
class StoreHouse {
private:
DynamicArray medicines;
Thing is, I though I also need to create the constructor of the storehouse, since medicines
is just an uninitialized dynamic array right now. So I did this (consider this to be right below the above code):
public:
StoreHouse();
And implemented it:
StoreHouse::StoreHouse() {
this->medicines = DynamicArray();
}
But now every time I create a new StoreHouse I get a Segmentation Fault
at the end of the scope where I created it. I think there is some sort of problem with the destructor, but I can't figure out what and why. If I remove the constructor for the store house (so the above 2 blocks of code wouldn't exist) and instead of calling StoreHouse store = StoreHouse()
I simply do StoreHouse store
everything works, no segmentation fault. I used the DynamicArray
class in other places and every time I used it I instantiated an object of it with DynamicArray da = DynamicArray()
, so I explicitly called the constructor every time. It worked without problems. Here, it doesn't seem to work. I am very new to C++ so I don't really understand what's going on, even after debugging. As I said, in the end I did get it to work if I removed that constructor, but I want to know what's going on and why it didn't work the way I though it would.