-1

i've run into a bit of a problem while creating my own game engine in C++. I want to have two objects:

an ObjectCreator class, and a Player class. The object creator can create a player, and the player can use the object creator to create bullets. The problem is, using both header files for each other would cause the game to not compile. Simply declaring the class in the header file without #include wont work, because i would not be able to access the functions that way.

Heres an example:

#include "Player.h"
class ObjectCreator
{
public:
ObjectCreator();
void CreatePlayer();
}

#include "ObjectCreator";
class Player
{
Public:
Player();
CreateBulletsWithObjectCreator();
}

So, does anyone have a solution to this problem? any help is appreciated :3

  • 1
    This will not compile anyway: `Public:` is a syntax error. – Bathsheba Nov 29 '13 at 10:59
  • @Bathsheba, its pseudocode, sry should've mentioned. – SolidSpy24 Nov 29 '13 at 11:08
  • @SolidSpy24 - Really - does not even look like pseudocode - not an algotithm in sight – Ed Heal Nov 29 '13 at 11:15
  • 1
    What is 'CreateBulletsWithObjectCreator'? it lacks a return value. You only have to include 'Player.h' in 'ObjectCretor.cpp' not in 'ObjectCreator.h' - because your class has no member of the type Player and no function takes an Argument of that type. So you can freely use and create Player Objects in ObjectCreator.cpp. Just don't mix declaration and implementation. – Constantin Nov 29 '13 at 11:17

1 Answers1

3

If you have a circular dependency, it's usually a smell of bad design. A common way to resolve this would be to extract the functionality in one part referenced by the other into a third class.

In your case, you could e.g. separate your ObjectCreator into a PlayerCreator and a BulletCreator. Doesn't seem to make any logical sense to have one class create all kinds of objects anyway.

Syntactically, there would be ways to also be able to live with a circular dependency. The trick is to only forward-declare the circularly referenced object in at least one of the header files instead of including its header; and then including the other header only in the source file. However, because of the smell of bad design, it is usually a better idea to do the redesign mentioned above.

codeling
  • 11,056
  • 4
  • 42
  • 71