Reputation: 21
I have been trying to use a const as the size of an array inside a class declaration. I know it works if I use a static const, but I am having trouble understanding why exactly. More specifically, why can I use const for some data members in a class, but must specify static const for others, as follows:
class Test
{
public:
static const int size = 10; // 1. Works. Must be static to use it as size of array
const int alpha = 20; // 2. Works, but cannot use as size of an array
const double beta = 10.0; // 3. Works
static const double gamma = 20.0; // 4. does not compile
int table[size]; // Works with size, but not alpha
};
I have read many explanations, but have not found an one (or at least one I understand) specifically for what makes case 1 different from case 4, and why I need to make the const static for the array.
Can anyone shed some light on this?
Edit: I'm using VS 2013 if that makes a difference
Upvotes: 2
Views: 132
Reputation: 141544
The difference is that:
const int alpha = 20;
is specifying that 20
is the default value which an object's alpha
would get if you don't specify any other value. However the class could easily have a constructor that overrides this, e.g.:
// header file:
struct S
{
S();
S(int);
const int alpha = 20;
};
// .cpp file
S::S(int): alpha(30) { }
S::S(): alpha(40) {}
So the value of alpha
could in fact be different for different objects. This means that the size of the object cannot depend on it, because all objects of the same type must have the same size and layout.
However in the case static const int size = 10;
, this specifies right then and there that size
does have value 10
and nothing later on can supersede this; so this can be used as array sizes and so on. There is only a single size
variable which is separate to any objects of the class.
Upvotes: 2
Reputation: 206567
but have not found an one (or at least one I understand) specifically for what makes case 1 different from case 4,
An array size can only be an integral expression can be computed at compile time. Since gamma
is of type double
, you cannot use it as the size of an array.
why I need to make the const static for the array.
A non-static
member exists only as a member of an object of the class. Its value is not usable without an object of the class. That throws up a catch-22 situation. You can't define the class without the size. You can't get the size without an object. A static
member solves that problem.
Upvotes: 0
Reputation: 663
C++ doesn't allow non-constant values for the size of an array. That's just the way it was designed. Array's size must be determined at compile time.
If you want a dynamically sized array, you need to allocate memory for it (and free it with delete when you're done).
Upvotes: -1