I believe what you're looking for is a vector
class. It's a contiguous array-like storage structure (nice stackoverflow question), and a C++ alternative to C arrays.
You can do it with a pointer, but since vector
is dynamically growing in size, it's not that important.
Here's an example from your example:
#include <vector>
class foo{
private:
std::vector<int> *vecPointer;
public:
foo(int size){
vecPointer = new std::vector<int>(size, 0);
// 0 as default value, can be omitted
}
~foo(){
delete vecPointer;
}
}
An alternative, if you just want to reserve memory, but don't actually have elements at the
time of class initialization, would be to just reserve the memory instead of filling it with concrete int
values. In that case, the constructor would look something like:
foo::foo(int size){
vecPointer = new std::vector<int>();
vecPointer->reserve(size);
}
The destructor does not change, and inside the class foo
, you can add object up to the reserved size with vecPointer->push_back(5)
, and you can add more objects than that in exactly the same way (only after that the vector size and the memory it takes will grow).
Also, do you really want to use pointers? You don't have to, you could just have a normal vector:
#include <vector>
class foo{
private:
std::vector<int> vec;
public:
foo(int size){
vec.resize(size, 0); // it's initialized as empty here
// alternative, with reserve:
// vec.reserve(size);
}
~foo(){
// no deletion needed like this
}
}
This way, everything is taken care of and you don't have to remember to delete.