Sign in to follow this  
fathom88

Silly Question On Static Arrays

Recommended Posts

I have a quick question on static arrays. I'm trying to define a class member as a static array. I keep on getting compile errors. How would you initialize it? If it were " static int MyVar;", I would do "int MyClass::MyVar = 0;" before I start defining the rest of my class. What do I do when it's "static int MyVar[MAX_VARS]; " Thanks. I know it's stupid question that I should I already know the answer to. Oops. I'm using C++ if you can't tell.

Share this post


Link to post
Share on other sites
If you want to have a predefined array with all zeros, you could do
int MyClass::MyVar[MAX_VARS] = { 0 };
in your implementation file.

If you want to have a predefined array with different values, you could do
int MyClass::MyVar[MAX_VARS] = { 1,2,3,8,4,-5000 };
in your implementation file. I assume that the count of numbers must match MAX_VARS (maybe I'm wrong here, and there is some fallback mode that fills up missed values).

You could also allocate an array by static initializer if using
int* MyClass::MyVar = new int[MAX_VARS];
in your implementation file. This may be more appropriate if you need a large array and could initialize it lazily.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this