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
You mean a fixed sized array? You could use
std::array
like this:Or if you want to support different sizes you need to resort to a class template like this:
std:array
has the added benefit of keeping the size information along with the member (unlike arrays which decay to pointers) and is compatible with the standard library algorithms.There is also a version that Boost offers (boost::array) which is similar.
No, it's not possible: As long as
size
is 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
size
into 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.Your code yields an error because compiler needs to know the size of data type of each member. When you write
int arr[N]
type of memberarr
is "an array of N integers" whereN
must be known number in compile time.One solution is using enum:
Another is declaring size as static const member of class:
Note that in-class initialization is allowed only for static class integers! For other types you need to initialize them in code file.