« Create a Dynamic Array class in C++

Create a class having the functionalities of a dynamic array

1class DynamicArray
2{
3
4public:
5 int *data;
6 int nextIndex;
7 int capacity;
8
9 DynamicArray()
10 {
11 data = new int[5];
12 nextIndex = 0;
13 capacity = 5;
14 }
15
16 // custom copy constructor
17 DynamicArray(DynamicArray const &d)
18 {
19 // this->data = d.data; // shallow copy
20
21 // deep copy
22 this->data = new int[d.capacity];
23 for (int i = 0; i < d.nextIndex; i++)
24 {
25 this->data[i] = d.data[i];
26 }
27
28 this->nextIndex = d.nextIndex;
29 this->capacity = d.capacity;
30 }
31
32 void operator=(DynamicArray const &d)
33 {
34 this->data = new int[d.capacity];
35 for (int i = 0; i < d.nextIndex; i++)
36 {
37 this->data[i] = d.data[i];
38 }
39
40 this->nextIndex = d.nextIndex;
41 this->capacity = d.capacity;
42 }
43
44 void add(int element)
45 {
46 if (nextIndex == capacity)
47 {
48 cout << "nextIndex == capacity" << endl;
49 int *newData = new int[2 * capacity];
50 for (int i = 0; i < capacity; i++)
51 {
52 newData[i] = data[i];
53 }
54 delete[] data;
55 data = newData;
56 capacity *= 2;
57 }
58 data[nextIndex] = element;
59 nextIndex++;
60 }
61
62 int get(int i) const
63 {
64 if (i < nextIndex)
65 {
66 return data[i];
67 }
68 else
69 {
70 return -1;
71 }
72 }
73
74 void add(int element, int index)
75 {
76 if (index < nextIndex)
77 {
78 data[index] = element;
79 }
80 else if (index == nextIndex)
81 {
82 add(element);
83 }
84 else
85 {
86 return;
87 }
88 }
89
90 void print() const
91 {
92 for (int i = 0; i < nextIndex; i++)
93 {
94 cout << data[i] << " ";
95 }
96 cout << endl;
97 }
98};

For full class code to try out the code yourself:

https://github.com/anishakd4/ds/tree/master/cn/oops