Public Group

# Having two classes both access each other

This topic is 3770 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## 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
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
Not sure how you have your application set up but perhaps in your header file you could pre-declare your enemy/character class, then in your cpp file you could include the proper header file

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
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
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).

1. 1
2. 2
Rutin
23
3. 3
JoeJ
20
4. 4
5. 5

• 23
• 40
• 23
• 13
• 13
• ### Forum Statistics

• Total Topics
631733
• Total Posts
3001928
×