# Having two classes both access each other

## Recommended Posts

I have a problem here. I have two classes: Character and Enemy with TakeDamage() functions. Now TakeDamage() takes the parameter of the attacker. So Character.cpp
void Character::TakeDamage(Enemy* &theEnemy)
{
//code
}


Enemy.cpp
void Enemy::TakeDamage(Character* &theCharacter)
{
//code
}


But my Library.h has this
//other header files
#include "Character.h"
#include "Enemy.h"


"Enemy.h" has access to "Character.h" but "Character.h" doesn't have access to "Enemy.h" since the Enemy header file comes first. Is there a way to have both classes access each other?

##### Share on other sites
Tristan85    221
Certainly,

It's called a forward declaration. Putting something along the lines of

class Enemy;

in "Character.h" will most likely solve the issue. I must warn you though that circular dependencies are generally considered to be 'bad practice'. The reasoning behind this, amongst other things, is that dependencies between classes should be minimized to improve maintainability.

Cheers,
Tristan

##### Share on other sites
gsGomer    122

Example:

Character.h
class Enemy; //pre-declareclass Character{public:...void TakeDamage(Enemy* &theEnemy);...};

Character.cpp
#include "Enemy.h"...void Character::TakeDamage(Enemy* &theEnemy)...

Same for the enemy class

Enemy.h
class Character; //pre declareclass Enemy{public:...void TakeDamage(Character* &theCharacter);...};

Enemy.cpp
#include "Character.h"...void Enemy::TakeDamage(Character* &theCharacter);...

I'm sure there are better ways to go about this, such as using some type of event system or object messaging system. However this method should work for an easy quick fix.

Hope that helps!

 Sorry for the "double advice" Seems Tristan beat me to the punch![/edit]

##### Share on other sites
Wow I learn a new thing about programming every day from Gamedev. Thanks for the help, Tristan and gsGomer :)

##### Share on other sites
stonemetal    288
Something to remember about forward declarations they will make it so that you can have a pointer you can't have a regular instance variable. Something odd I noticed about your code, why are you using a reference to a pointer?

##### Share on other sites
CzarKirk    100
If they are using a similar function, couldn't you have one class inherit from another? Isn't an enemy just a character that can't be controlled, and minus a few other things?

Instead of sending the whole enemy/character to the function, maybe only send the information that is actually required (attack stats).