We made a dynamic array class during lecture and the instructor copy-pasted the copy_constructor code on the assignment_operator_overload. But don't we need to delete the existing dynamic array first for the assignment operator ? (Please refer void "operator=(DynamicArray const &d){}" function at the 29th line)
#include <iostream>
using namespace std;
class DynamicArray {
int *data;
int nextIndex;
int capacity; // total size
public :
DynamicArray() {
data = new int[5];
nextIndex = 0;
capacity = 5;
}
DynamicArray(DynamicArray const &d) {
//this -> data = d.data; // Shallow copy
// Deep copy
this -> data = new int[d.capacity];
for(int i = 0; i < d.nextIndex; i++) {
this -> data[i] = d.data[i];
}
this -> nextIndex = d.nextIndex;
this -> capacity = d.capacity;
}
void operator=(DynamicArray const &d) {
// I think here we should add // delete []this->data;
this -> data = new int[d.capacity];
for(int i = 0; i < d.nextIndex; i++) {
this -> data[i] = d.data[i];
}
this -> nextIndex = d.nextIndex;
this -> capacity = d.capacity;
}
void add(int element) {
if(nextIndex == capacity) {
int *newData = new int[2 * capacity];
for(int i = 0; i < capacity; i++) {
newData[i] = data[i];
}
delete [] data;
data = newData;
capacity *= 2;
}
data[nextIndex] = element;
nextIndex++;
}
//Here add can only modify the previous, present and just_next index.
void add(int i, int element) {
if(i < nextIndex) {
data[i] = element;
}
else if(i == nextIndex) {
add(element);
}
else {
return;
}
}
};
int main() {
DynamicArray d1;
d1.add(10);
d1.add(20);
d1.add(30);
d1.add(40);
d1.add(50);
d1.add(60);
d1.add(9, 100);
d1.print();
DynamicArray d2(d1); // Copy constructor
DynamicArray d3 = d1; // Copy constructor
d3 = d1; // Assignment operator
}
// I think here we should add // delete []this->data;You may be right, you need to de-allocate the memory previous data, but this is only when capacity is different, if it's same then you can just copy the new data.void add(int i, int element)is incorrect btw, or at the very least the contract is weird. I'd expect this to do an insertion of an element at indexi, but in case you specify the index of an existing element, you simply overwrite the element. For insertion you'd first need to allocate a new array, if necessary, and move the elements with a index >= the insertion index back by 1 and only then write the element.