I’m sort of new to C++ (coming from Java) and I want to declare an array object in a class, but it requires an integer value in its template parameters.
I figured I’d have to make a pointer to an array class, but it does not work..
I want to make something like:
class foo{
private:
array *myArray;
public:
foo(int size){
//This line may be terribly wrong, but you see what I mean
myArray = new array<int,5>();
}
~foo(){
free(myArray);
}
}
Though, the correct initialization of an array object is:
array<int,5>
but this way does not let me choose length in runtime.
I highly recommend that you pick up a good introductory C++ book, and forget about Java. Seriously, thinking in Java is counterproductive when learning C++. They may have similar syntax but they have very, very different semantics.
The issues you’re having is related to fundamental concepts of the language. You have to learn the fundamentals from a good C++ introductory book before moving on.
std::array(if that’s what you’re using) is not the correct class to use for this particular application, because of the fact that you want to choose the length at runtime. The size of thestd::arrayis fixed at compile-time.You should use
std::vectorinstead, which allows you to specify (and change) the size at runtime.The standard containers such as
std::vectormanages the memory for you; you don’t need tonewordeletethe standard containers. The standard containers exist because so you don’t have to manually deal with memory yourself.Notice that I didn’t use pointers,
new,delete,malloc(), orfree()anywhere here. You often don’t need pointers for many, many cases in C++. Contrary to popular belief, there’s very little manual memory management that you actually have to do when using modern C++ techniques. In fact, if you’re usingdeleteorfree()in your C++ code, you’re probably doing it very wrong.I would like to stress again the importance of a good introductory C++ book in assisting you with the language. Any good intro C++ book will cover
std::vectorand how to use it to your advantage. Other resources such as astd::vectorreference can also be of assistance. Familiarize yourself with them.