The reason you get compiler errors is the line:
T this_array[start_size];
On this line, your Tarray
really contains start_size
instances of T
It will not contain a pointer or a link to these instances - they will be part of the same memory block that contains the Tarray instance variables. This would make the class size depend on start_size, and start_size is not known at compile time. The size of any C ++ class must be known at compile time, this is not possible.
There are two ways to solve this problem:
- Select an array of
T
instances on the heap using the new array. This is what std::vector
does. Writing such a class and its proper behavior when copying / moving / extending / etc are difficult and tedious, so I would recommend using std::vector
instead. - Commit the number of instances of T and pass it as a template parameter
i.e:.
template<typename T, std::size_t N> class TArray { ... T this_array[N]; ... }
This is what std :: array (C ++ 11 only) and boost :: array do. Again, I would recommend using one of them instead of writing your own. If it's not homework, of course ...
Finally, it is worth noting that this is a mistake:
~Tarray(){ delete[] this_array; }
this_array
not allocated new
, so you should not delete
it. If the array is part of the class as it is (instead of having to separate the heap separately and belong to the class), it will be destroyed by default along with the rest of the class. The delete
call is not only superfluous, it will almost certainly cause a failure.
source share