Archived

This topic is now archived and is closed to further replies.

Zoomby

init array with const value in class

Recommended Posts

hi I want to create a local array with a const number of values in a class. I tried the code below, but it won''t compile. Is it possible to do that? I want the array to be local, and don''t want to use #defines to set the array''s size.
class Hello
{
	static const int value;
	char bla[value];

};
const int Hello::value=3;
 
bye chris

Share this post


Link to post
Share on other sites
"static const int value;"

Constant values have to be initialized otherwise they may as well be normal integers, I''m not sure what the static operator does though.

"const int Hello::value=3;"
The :: operator is to access functions inside the class to acess a variable it would be hello.value = 3;

And you haven''t yet created an instance of the class like this "Hello hello"

" and don''t want to use #defines to set the array''s size."

Theres no reason to use defines to set the arrays size anyway (although it can be handy in bigger programs) just something like "char chararray[10] would do the same thing.

you can set an arrays size at runtime but you need to learn about pointers first. I''d suggest learning more about classes and the const operator first however.

Share this post


Link to post
Share on other sites
value is a static const int, so this is allowed:

class Hello
{
    static const int value = 3;
    char bla[value];
};


I''m not sure how much of this is allowed for other static const types -- maybe someone else can help here.

Share this post


Link to post
Share on other sites
use in-class definition:
static const int value = 3;

You could also use:
enum { value = 3 };

This is more portable because some compilers don''t support in-class def.

oh and this only works on integral types ( int, char ,etc)

Share this post


Link to post
Share on other sites
Perhaps he does want to change it at run-time, but I''d guess otherwise, just because his value is a static const and he is setting the const to an unchanging value. And as people said earlier, some older compilers don''t like you defining static const values in the class definition, but in that case, you can just use the enum hack like people did before defining static const values in the class definition was part of the language standard.

Share this post


Link to post
Share on other sites