PDA

View Full Version : A SW engineering question (C++, relation between classes)


lakibuk
06-17-2007, 07:31 AM
I use a main object called, which is composed of all the objects that make up the game.

CGame
/ \
CLevel CGraph ...

Now i often need to call a method from another object.
Eg. CLevel needs to call a function from CGraph.
For this reason every object gets a pointer to the main CGame obj.
So i call the function CGraph function from inside of CLevel like this:
this->p_game->CGraph.draw()

Is this a good way? It feels stupid and awkward.
How do you handle communication between objects in C++ ?

benko
06-17-2007, 07:45 AM
The typical "Game" class is singleton (i don't know if yours is already), so you can get the pointer to the only one CGame instance with Game::GetInstance()

Anyway, why do you need to call drawing methods from the level? Wouldn't it be better to handle that from the game class?

I have a base class Sprite which is able to draw itself. Although Sprite instances are created from Level class, it's the Game class which calls Sprite's Update and Draw methods in each frame.

lakibuk
06-17-2007, 07:56 AM
Singleton? Never heard this word. Google says it's a design pattern? I will take a look at it.

Anyway, why do you need to call drawing methods from the level?...
it's the Game class which calls Sprite's Update and Draw methods in each frame.
I am doing it similar. But in the sprite's Draw() you need the blitting-functions of the Graphics object, don't you?

benko
06-17-2007, 08:06 AM
I am doing it similar. But in the sprite's Draw() you need the blitting-functions of the Graphics object, don't you?

Actually, I don't like having a "graphics" object. I'm more fan of having a Engine class with static functions, which would wrap the graphics, i/o and sounds API. For example, you could have in your Engine class a function called DrawImage which gets as input one image, the x and the y. So...

Sprite::Draw() {
Engine::DrawImage(graph,x,y);
}

Just that. Remember that static functions are class "methods" than can be called with no object instance.

Besides that, whenever a sprite is created, it adds itself to a List of sprites (or the Abstract Data Type you chose) belonging to the class Game.


Singleton? Never heard this word. Google says it's a design pattern? I will take a look at it.


It's a very common and simple design pattern. It's used whenever you need a class only have one instance (or a few) of itself. Just remember it is not a excuse to use "fake global" variables ;)