Yes, this code
class_name(int n, const int d)
{
float arr[d];
map = arr;
}
is a bad idea, for 2 reasons
float arr[d];
creates a local variable in stack, so it ceases to exist at the end of the block. So map
becomes a dangling pointer. If you needed dynamic size allocation, you should just use std::vector<float> map
and avoid a lot of hassle.
float arr[d];
is a variable length array, and C++ does not support those. Making d
be const
does not help, it has to be an actual constant, not const
variable.
Solution: Since you say the array length can be determined at compile time, this is perfect fit for a template:
template <std::size_t N>
class class_name
{
public:
std::array<float, N> map { {} }; // { {} } causes value initialization of everything to 0
// actually above could be `float map[N];` but it has the C array gotchas
class_name(int n)
{
// not sure what n is for...
}
};
And to declare a variable of this class:
class_name<5> obj; // obj.map size is 5