How to declare a constant array in class with constant class variable? Is it possible.
I don’t want dynamic array.
I mean something like this:
class test
{
const int size;
int array[size];
public:
test():size(50)
{}
}
int main()
{
test t(500);
return 0;
}
the above code gives errors
No, it’s not possible: As long as
sizeis a dynamic variable,array[size]cannot possibly be implemented as a static array.If you like, think about it this way:
sizeof(test)must be known at compile time (e.g. consider arrays oftest). Butsizeof(test) == sizeof(int) * (1 + size)in your hypothetical example, which isn’t a compile-time known value!You can make
sizeinto a template parameter; that’s about the only solution:Usage:
Test<50> x;Note that now we have
sizeof(Test<N>) == sizeof(int) * (1 + N), which is in fact a compile-time known value, because for eachN,Test<N>is a distinct type.