Need help with simple program

Recommended Posts

Hello, I need some help with a very simple program.
int main()
{
GameInit();
int done=0;
while(done == 0)
{
SDL_Event event;
while ( SDL_PollEvent(&event) )
{
GameMain();
}
return 0;
}
That part works fine, what I want to do next is to make an object in GameInit() and be able to access it in GameMain().
int GameInit()
{
Sprite TankUp(4);
return 0;
}
int GameMain()
{
TankUp.Update();
return 0;
}
class Sprite
{
public:
int frame;
Sprite (int);
void Update();
};
Sprite::Sprite(int f)
{
frame=f;
}
void Sprite::Update()
{
frame++;
}
Right now this wont compile. How can I make it so GameMain can access the sprite TankUp. This may be really basic, but I dont know how to do it, maybe its not allowed.

Share this post

Link to post

Share on other sites

The simplest option would be to make Tankup a global variable (place the initialization line outside of any function, preferably just after your include directives). If you are a beginner, this would definitely be your best bet. Look up variable scoping for more information.

Also make sure that you fix the error that alnite discovered.______________________________________________________________The Phoenix shall arise from the ashes... ThunderHawk -- ¦þMySite______________________________________________________________

Share this post

Link to post

Share on other sites

quote:Original post by Thunder_Hawk Tankup isn''t an array (that''s a constructor argument specifying the first frame).

Ah I see. my mistake. Sorry.

Globals aren''t entirely evil. They just tend to make larger programs more confusing, and it cracks the fundamental of ''independence-ism''. If one of your functions uses a global, that function can''t run if the global is removed.

Here''s another alternative:

int main(){ Sprite TankUp(4); // code goes here GameMain( TankUp );}

int GameMain( Sprite& tank ){ tank.Update();}

0

Share this post

Link to post

Share on other sites

would also solve that problem, even though i sometimes think its kind of silly to wrap your whole program in a class just for the sake of "clean" coding and being able to say "ha, see? now they arent global anymore". but as you dont need more than one Game you could make everything static, effectively its all global again and not different from placing it in a namespace, except being able to regulate access to different members via private and public. making the constructor private avoids creating instances.

of course now someone will come up and tell you about singletons, another concept i find highly overrated and too often used without thinking (just like quaternions *cough*).

0

Share this post

Link to post

Share on other sites

quote:Original post by Trienco of course now someone will come up and tell you about singletons, another concept i find highly overrated and too often used without thinking (just like quaternions *cough*).