I'm making a Dynamic Array with templates and classes.
This is the code I'm having issues with:
template<typename GType>
class GArray
{
GType* array_type = nullptr;
int size = 0;
public:
GArray(GType Size)
{
size = Size;
array_type = new GType[size];
for (int i = 0; i < size; i++)
array_type[i] = NULL;
}
void Push(GType Item)
{
size++;
GType* temp = new GType[size];
for (int i = 0; i < size-1; i++)
temp[i] = array_type[i];
temp[size] = Item;
delete[] array_type;
array_type = temp;
temp = nullptr;
}
GType& operator[] (int Index)
{
if (Index >= 0 && Index < size)
return array_type[Index];
}
};
int main()
{
GArray<int> arr(2);
arr[0] = 10;
arr[1] = 20;
arr.Push(30);
// print array
for (int i = 0; i < arr.Size(); i++)
cout << arr[i] << endl;
return 0;
}
In the main(), when I print the whole array values, the last one (which should be 30) is an undefined value (like -842150451).
With several tests, I can say that INSIDE the Push() function, the array_type pointer changes. When I come back to the main(), it's like array_type didn't change, it's the same as before.
[]does not always return a value! Should not compilesize = Size;)returnwith no value; this results in undefined behavior in a value-returning function." — In clang and gcc-Werror=return-typecan be used to emit an error.