I’m trying to create a Breakout clone using C++, and so have several objects (like ball, paddle, powerupicon, block, etc). I understand that it’s bad practice to have them at global scope, so they’re initialized inside main(). The problem comes in with needing to do stuff with those objects from inside other functions (like redraw(), or reset_game()). The only method I can think of to do this would be to pass references of the objects into each function, but I’m not sure if this is the best approach.
Basically, what’s the best way to do stuff with these objects from within a function? Pass them by reference? Make them global but within a namespace? Or something completely different?
A simple (not necessarily flexible or powerful) approach is to define a base
game_objectclass that defines your interface with game objects, and store those. Your objects inherit from it.:Now you have a common way of using a game object. Next, you can store these in a map (preferably an
unordered_mapif you have Boost, TR1, or C++0x), and make that map globally available:You define this in a translation unit (either
main.cppor agame_object_manager.cpp) somewhere. Lastly, you use it by inserting things by name:And use it:
Again, this is a simple solution and isn’t necessarily robust, a best practice, or flexible. But for a first game, it’ll work fine. (To improve it, you want to look into exception safety, smart pointers, and other things (game books). I recommend you do this before you try to make games.)