I recently came across an issue regarding some classes having access to other classes' members. For instance, I have classes such as TextField, Button, Menu etc... and I have a master class Game. I want every instance of my other classes knowing their parent's location in memmory as to be able to access some of its members directly, something like this:
Although -- this approach requires you to fill the 'game' pointer for every created object. If it's assumed there is only one global Game object, you can take a different approach.
1 2 3 4 5 6 7 8
// in game.h
class Game
{
// ...
public:
static Game& GetGame(); // return a reference to the global Game object
};
This way other objects can just call Game::GetGame() when they need to access the Game, and they don't need to own their own pointer to it. It's a little less flexible because it limits you to 1 Game, but is a bit easier to work with.
Any .cpp file that uses a Game pointer (like accesses any members or calls any functions, etc) will need to #include "game.h". There is no way around that.
Ok, thanks a lot, Disch!
Since Game IS a singleton, it makes perfect sense to take the GetGame aproach! :D
Here's my code, any comments or sugestions appreciated!
//Game.h
class Game
{
public:
static Game *instance;
private:
{...}
public:
Game();
~Game();
{...}
static Game* getGame() { assert(instance); return instance; }
};
//Game.cpp
#include "Game.h"
Game* Game::instance = NULL;
Game::Game()
{
//kill app if there is more than one instance of Game
assert(!instance);
instance = this;
{...}
}