I am trying to create an array data structure in C++ using classes. The idea is that the array has a predefined length to it and whenever there is need for extra space, the array gets reallocated to double it's previous length. But, there is something wrong with the code that I am unable to figure out. It displays garbage values for items that should have been allocated.
Following is the relevant code:
#include <iostream>
using namespace std;
class Array
{
private:
int length = 8;
int occupied_length = 0;
int* array = new int[length];
void reallocate_array()
{
array = (int*) realloc(array, length*2);
length = length * 2;
}
public:
Array()
{
cout << "How many elements do you want in the array: ";
cin >> occupied_length;
if (occupied_length > length) // In case array is full, it needs to be reallocated
reallocate_array();
for (int i = 0; i < occupied_length; i++)
cin >> *(array + i);
Print();
}
~Array() { delete array; }
void insert(int pos, int data)
{
if (pos > occupied_length) {cout << "Invalid Position!\n"; return; }
occupied_length += 1;
if (occupied_length > length) { reallocate_array(); }
if (pos == occupied_length){ *(array+occupied_length) = data; return;}
for(int i = occupied_length-2; i >= pos-1; i--)
*(array+i+1) = *(array+i);
*(array + pos - 1) = data;
}
int size()
{
return occupied_length;
}
void Print()
{
for(int i =0; i <occupied_length; i++) { cout << *(array+i) << " "; }
cout << endl;
}
};
int main()
{
Array arr;
arr.insert(7,45);
arr.Print();
arr.insert(3,35);
arr.Print();
arr.insert(4,86);
arr.Print();
cout << arr.size() << endl;
return 0;
}
The output of the above program is as follows:

On top of that, the program does not immediately stop execution after the last cout statement. It waits for a second or two.
To sum up what comments are saying:
reallocthe second argument is the number of bytes, so you would need to multiply bysizeof(int). But again, don't userealloc.You might as well make this a templated class to avoid repeating yourself.
Of course, with the contents private you'll need to implement public member functions to gain access to the data and size. You'll also want to implement iterators.