Link to home
Start Free TrialLog in
Avatar of kushcu
kushcu

asked on

static member variables

The following code fragment compiles fine with MSVC++ 6.

-- AlienShip.h

class AlienShip : public Sprite  
{
...
private:
     static HBITMAP m_hSprite;
...
};

-- AlienShip.cpp

#include "AlienShip.h"

HBITMAP AlienShip::m_hSprite = NULL;
...

Later, I load a bitmap with the help of the bitmap handler, and use this static variable -m_hSprite- throughout my program. (In fact, this is irrelevant, it's just supposed to give you an idea.)

Now, I'm thinking of doing an animation, and I need 7 bitmap handlers. I couldn't find anything said on static member variable arrays, so tried the following:

-- AlienShip.h

class AlienShip : public Sprite  
{
...
private:
     static HBITMAP m_hSprite[7];
...
};

-- AlienShip.cpp

#include "AlienShip.h"

HBITMAP AlienShip::m_hSprite[0] = NULL;
...


and received the following error message: error C2466: cannot allocate an array of constant size 0.
I tried some other combinations hoping that they would work, but no.

So, the point is, can I do what I want? If yes, how? Please note that I need to use static.
ASKER CERTIFIED SOLUTION
Avatar of Axter
Axter
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
In other words (and I think that is what Axter wanted to say): You'd better be sure to actually initialize a static mamber...
Avatar of kushcu
kushcu

ASKER

Axter, thanks! Could you also please tell me why it doesn't work the other way around? (some simple comment would help.)
The class declaration is declaring an array of 7, but the variable initiation is declaring an array of zero.

Just the fact that it's zero will make the compile fail to compile the code.

Example:
int main(int argc, char* argv[])
{
 char xyz[0] = NULL;//This line fails to compile
 char xyz2[0];//This line also fails to compile
 return 0;
}

Now if you wanted to just initiate the first item in the array, you could still do that, as long as the array is more then zero, and it matches the class declaration.
Example:
HBITMAP AlienShip::m_hSprite[7] = {NULL}; //Use brackets for an array.

Avatar of kushcu

ASKER

OK, that clears up the issue for me. Thanks for the help.