[comp.lang.c++] use of const within a class to dimension arrays

jmartin@secola.Columbia.NCR.COM (John Martinez) (06/20/91)

Is there any way to use a const within a class as the size of an array
which is also a member of the class?


Consider the following sample code:
(if anybody cares, it's in BC++ under DOS, but I think this is a _language_
 problem.... )
// ************************************
class Minimal {
   static const int ARRAY_SIZE;
   static int array[ARRAY_SIZE];   // "error - constant expression required"
				   //  (within the brackets, presumably)
};
const int Minimal::ARRAY_SIZE=10;
// ************************************


This generates an error, presumably because ARRAY_SIZE, while const, doesn't
count as _really_ constant until it is given a value.

Obviously there are ways to define the array I want - I could allocate it
dynamically, I could use #define for the ARRAY_SIZE, etc. but I'm trying to
find a "well-behaved" solution to what ought to be really easy to do in the
language, but isn't. I am _trying_ to follow these rules:

1) Don't use #define if you can use a const (type-checking, etc.)
2) Don't make things visible where they shouldn't be; in this case, ARRAY_SIZE
   is specific to the implementation of Minimal and no where else, so ideally,
   it shouldn't be visible to any other other code.
3) Use "constants" (loosely defined to include #defined values) instead of
   hardcoded values whenever possible and especially if the value will be
   referenced all over and is likely to be modified as the program evolves.
4) In general, if you can do something just as easily without using the heap,
   do it that way.


So, is there any "nice" way to do what I want to do, or do I have to "cheat"?

Thanks.

-(--John
jmartin@secola.Columbia.NCR.COM (upper/lower case IS significant!)

-- 
John V.Martinez
NCR Network Products Division
jmartin@secola.Columbia.NCR.COM
(803)739-7671 vplus:633-7671

steve@taumet.com (Stephen Clamage) (06/20/91)

jmartin@secola.Columbia.NCR.COM (John Martinez) writes:

>Is there any way to use a const within a class as the size of an array
>which is also a member of the class?

No, unless you use an enum constant (ugh).

>class Minimal {
>   static const int ARRAY_SIZE;
>   static int array[ARRAY_SIZE];   // "error - constant expression required"
>};
>const int Minimal::ARRAY_SIZE=10;

>This generates an error, presumably because ARRAY_SIZE, while const, doesn't
>count as _really_ constant until it is given a value.

No, the array size must be a compile-time constant, and declaring a member
	static const int ARRAY_SIZE;
or
	const int ARRAY_SIZE;
does not create a compile-time constant, but does create storage for a
class field.

I agree that this is a language deficiency.  At the moment, the best
you can do is this:

class Minimal {
   enum { ARRAY_SIZE = 10 };
   static int array[ARRAY_SIZE];
};
-- 

Steve Clamage, TauMetric Corp, steve@taumet.com