Advertisement

Catch-22

Started by March 09, 2000 02:05 PM
1 comment, last by zaphod 24 years, 6 months ago
Ok heres my problem: I''m programming a simple 2d space shooter in c++ (no surprises there then) I''ve got a ''player'' class and an ''enemy'' class. For the purposes of collision detection they both need to refer to each other, so, say, the player.missiles.run(enemy* e) method needs a pointer to an enemy which it uses to detect a collision with that enemy and affect the enemy accordingly. Also the enemy.missiles.run(player* p) function takes a pointer to a player for the same reason. Uh-oh, catch-22, to define the player class I need to have defined the enemy class and to define the enemy class I need to have defined the player class! At the moment I have solved this problem by creating a third class ''collision_detect(player* p, enemy* e)'' which is defined after the player and enemy classes, but this seems like ugly code. For example, the player.run() method calls a method cannon.run() which calls a method missile.run() for an array of missiles. Rather than having the code for detecting and acting on a collision between a misile and a given enemy *here*, it resides in a different class entirely (collision_detect). This seems against the idea of OOP. Any ideas, or am I just being fussy? Thanks a lot Felix. </i>
What you need to do is forward declare each class in the header for the other.

In player.h:

class enemy;

class player {
void run( enemy* );
};

And the opposite in enemy.h.

You then need to include player.h in enemy.cpp (and vice versa).
Advertisement
LordFoul''s solution is correct for solving circular dependancies. We''ve all ran into this problem before. However, I think you might be able to solve this problem a different way. Make a virtual base class called ScreenObject that has a method for detecting colisions that takes a ScreenObject pointer. Then have the player and enemy classes inherit from ScreenObject. This might be what you are looking for since it allows you to do some other cool stuff.
Let me know if this works for you,
Eck
eck@home.com

EckTech Games - Games and Unity Assets I'm working on
Still Flying - My GameDev journal
The Shilwulf Dynasty - Campaign notes for my Rogue Trader RPG

This topic is closed to new replies.

Advertisement