# Classes calling each other

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

## Recommended Posts

Hi all,

Having a problem with my coding...

I'm trying to get classes to talk to each other freely. For example my player class must be able to speak to my weapon class. Weapon has to be able to talk BACK to player class to check for ordnance collisions and stuff (FYI haven't got a clue how to do that yet, but paving the way!).

Now I've tried setting up pointers for weapon class inside the player class OR vise versa... which is fine, this works. However as soon as I try to set up a pointer in BOTH classes to talk to each other it won't compile.

I've tracked this problem down to the fact that I can't have the following due to recursive includes (is that what it's called?)
[source lang="cpp"]
// Filename: playerclass.h.
#include "weaponclass.h"

class PlayerClass
{
//blah blah blah

private:
WeaponClass* weapon;

};[/source]

[source lang="cpp"]
// Filename: weaponclass.h.
#include "playerclass.h"
class WeaponClass
{
//blah blah blah
private:
PlayerClass* player;
};[/source]

Is there way to do this without the compiling errors?

I have though of have a class that works as a communicator with the others. Maybe implementing this into the engineclass, but I wasn't sure if this is classed as good practice...

Any help would be greatly appreciated...

Mike

##### Share on other sites
Ignoring any design issues, because it does sound a bit strange to me why a weapon need to have a player, the problem with mutual referencing in this case can be solved with forward declaration. Neither class need to know the full definition of the other, so you don't need to include its header. You only need to forward declare the types in order to define pointers to them.
 // Filename: playerclass.h. class WeaponClass; // foward declare the indentifier 'WeaponClass' as a class type class PlayerClass { //blah blah blah private: WeaponClass* weapon; }; 

##### Share on other sites

 // Filename: playerclass.h. //header file uses a pointer to a WeaponClass, so needs to know about its existence, but not its implementation class WeaponClass; class PlayerClass{ private: WeaponClass* weapon; }; ----- // Filename: playerclass.cpp #include "weaponclass.h" 

<quote>
talk BACK
</quote>

Best to avoid circular dependencies if you can. They tend to harm the modularity and readability of your code.

edit: too late Edited by eppo

##### Share on other sites
It's always a good idea to show the actual compiler errors. The whole point of them is that they're supposed to tell you (us) what's wrong!

It would also be a good idea to simmer down the code to a minimal compilable example. For example, I don't know if you've omitted header guards/"#pragma once" for brevity or if they really don't exist.

So I'm going to work on these assumptions:

1. You have appropriate header guards, or are using "#pragma once"
2. I'll assume the compiler error is something along the lines of "C++ forbids declaration of 'PlayerClass' with no type".

Ok, note how you have circular inclusion: playerclass.h includes weaponclass.h includes playerclass.h ...
Recall also that #include is somewhat like copy-and-pasting a header at the point of inclusion.

So after the preprocessor has done its work, we end up with something like this:

 #ifndef WEAPONCLASS_H_ #define WEAPONCLASS_H_ // Filename: weaponclass.h // --- begin #included playerclass.h --- #ifndef PLAYERCLASS_H_ #define PLAYERCLASS_H_ // Filename: playerclass.h. // --- begin #included weaponclass.h --- #ifndef WEAPONCLASS_H_ // WEAPONCLASS_H_ already defined at this point due to header guards. // Circular inclusion has no effect. #endif // WEAPONCLASS_H_ // --- end #included weaponclass.h --- class PlayerClass { // blah blah blah private: WeaponClass *weapon; }; #endif // PLAYERCLASS_H_ // --- end #included playerclass.h --- class WeaponClass { // blah blah blah private: PlayerClass *weapon; }; #endif // WEAPONCLASS_H_ 

Note how in the resulting translation unit, we've attempted to use the symbol "WeaponClass" as the type of a member of PlayerClass, even though "WeaponClass" hasn't been declared anywhere, thanks to the header guards and circular inclusion. Because there's no declaration, the compiler doesn't know what "WeaponClass" is, or how to treat it.

The way around this is to use forward declarations rather than inclusion. For example:

 #ifndef PLAYERCLASS_H_ #define PLAYERCLASS_H_ // Filename: playerclass.h class WeaponClass; class PlayerClass { //blah blah blah private: WeaponClass *weapon; }; #endif // PLAYERCLASS_H_ 

Then do the same thing in weaponclass.h. In your .cpp files you can #include both headers. I'll leave you to figure out why that works (just follow the copy-and-paste the preprocesor does and remember that it's valid to have multiple declarations that aren't definitions).

EDIT: and perhaps somewhat off topic, but having a weapon that knows about the player sounds a bit fishy to me. Edited by e?dd

##### Share on other sites

Weapon has to be able to talk BACK to player class to check for ordnance collisions and stuff (FYI haven't got a clue how to do that yet, but paving the way!).
[/quote]
This is a dubious requirement. There are better ways to design this.

On a side note, there is probably no need to call your classes FooClass. Most coding conventions use an uppercase type names, with lowercase variable names to disambiguate:
 class Weapon; class Player { // ... private: Weapon *weapon; }; 
It is up to you though, it is a stylistic choice.

##### Share on other sites
Thanks all - forward declarations are obviously whats needed here.

As for WHY weapon needs to contact the player class allow me to explain - I'd be interested in your input on this matter as well.

PlayerClass fires a weapon. Therefore contacts WeaponClass (which handles all bullets, bombs and the like) and create a new bullet to fly across the screen.

Now to check the collision of bullet and player ship I have weaponclass cycle through all the bullets and check their positions against the players ships, hence why weapon class needs to contact playerclass.

But I'm guessing from your above comments that this perhaps might not be the best approach?

@edd, Yes I did include header guards. Will endevour to include more accurate code and error messages next time - thank you for the help

##### Share on other sites
Hang on...

Just remembered that weaponclass actually sets up a linked list of OrdnanceClass objects to handle the individual bullets and the like... However according to my above thoughts they still need to contact the playerclass to check for collisions...

##### Share on other sites
Why does the player class check for collisions?

I can understand that the player might expose a bounding box (or cylinder, or whatever) and its velocity to allow external collision routines to work out any collisions, and what the collision response should be. Roughly:

 bounds, velocity = world.calc_collision_response(player.bounds, player.velocity, dt) player.bounds = bounds player.velocity = velocity 

The collision detection/response code is then entirely divorced from the player. This means it can be used for other things too (NPCs, vehicles, ...)

Similarly for weapons. If you've got stuff like sniper rifles, shotguns, etc, all that's really needed is:

 rays = player.weapon.get_spread(player.position, player.orientation); // might have many rays for a weapon with 'spread', like a shotgun for ray in rays: target = world.check_ray_hit(ray.origin, ray.direction) if target target.register_hit(ray.force, ray.penetration) 

Here, the player's details (position and orientation) are indeed used to calculate what the weapon would hit. But that doesn't mean the weapon has to know about who's holding it. In fact, the code would look exactly the same for the player, or for an NPC.

The code is probably overly simplistic, but you really want to avoid the situation where every class knows about every other class. In other words, you want to reduce coupling. This means that making changes reduces the rippling effect that's often seen when refactoring.

There are other benefits to this kind of separation too. You can group stuff like collision tests together to improve locality and allow vectorization. Edited by e?dd

##### Share on other sites
Cool Many thanks,

I will admit that A LOT of that collision detection went over my head (as I said I'm learning as I go) . Think I'll do loads more research before I continue design/developing.

Again many thanks!

1. 1
Rutin
28
2. 2
3. 3
4. 4
5. 5

• 13
• 11
• 10
• 13
• 20
• ### Forum Statistics

• Total Topics
632949
• Total Posts
3009415
• ### Who's Online (See full list)

There are no registered users currently online

×