Suppose I have a class...
class Foo
{
public:
Foo(int size);
private:
const int size;
int data[];
};
Supposing that the size field is set immediately at instantiation, how can I set the length of data
based on that size input?
I would ordinarily use a std::vector
here, but I am writing a library for Arduino, so that won't fly, and I'm trying to avoid external dependencies if I can.
You are out of luck here, as C++ must know the size of the array at compile time (in other words, the
size
must be a constant expression). Your options are to either use dynamic allocationthen allocate with
new int[size];
in the constructor initialization list, or, better, usestd::unique_ptr<>
(C++11 or later), which is a light wrapper around a raw pointer and deletes its allocated memory at scope exit, so you won't have to manuallydelete[]
A third option is to make
Foo
a non-type template class (assuming you know the size at compile time, which is what it seems to be happening, at least judging from your question)