0

For example, I want to create a game, which has a GameFlow to control the game event flow, also I have some controllers (e.g.:PlayerAttackController,EnemyControllerController) for different flow.

GameFlow used to switch controllers, controllers notify GameFlow to change state:

to simple the code I don't use .cpp and use public property only:

GameFlow.h

class GameFlow{
public:
    int state;
    IController* controller;
    void changeState(){
        if(controller!=NULL){
            delete controller;
        }
        if(state==0){
            controller=new PlayerAttackController();
            controller->gameFlow=this;
        }else if(state==1){
            controller=new EnemyAttackController();
            controller->gameFlow=this;
        }
        .
        .
        .
    }
};

IController.h

class IController{
};

PlayerAttackController.h

class PlayerAttackController : public IController{
public:
    GameFlow* gameFlow;
    void buttonPressed(){
        //some player attack code
        .
        .
        .
        gameFlow->state=1;
        gameFlow->changeState();
    }
};

(other controllers are similar)

Now it is clear that GameFlow contains Controller, each controller contains GameFlow, is there any method to break the circular dependency between GameFlow and Controller?

ggrr
  • 7,737
  • 5
  • 31
  • 53

1 Answers1

2

Don't define your member functions in-line with the classes. Instead, declare them in the classes (only telling the compiler they exist) and define them afterwards (probably in a .cpp file for each class, though this is not the only possible layout).

In GameFlow.h:

class GameFlow{
public:
    int state;
    IController* controller;
    void changeState(); // this is a declaration
};

In GameFlow.cpp, include GameFlow.h and PlayerAttackController.h, then:

// this is a definition
void GameFlow::changeState()
{
    if(controller!=NULL){
        delete controller;
    }
    if(state==0){
        controller=new PlayerAttackController();
        controller->gameFlow=this;
    }else if(state==1){
        controller=new EnemyAttackController();
        controller->gameFlow=this;
    }
    .
    .
    .
}

Same for PlayerAttackController. In PlayerAttackController.h:

class PlayerAttackController : public IController{
public:
    GameFlow* gameFlow;
    void buttonPressed(); // this is a declaration
};

In PlayerAttackController.cpp, include both headers and:

// this is a definition
void PlayerAttackController::buttonPressed(){
    //some player attack code
    .
    .
    .
    gameFlow->state=1;
    gameFlow->changeState();
}

You'll want to define your functions in .cpp files anyway for other reasons - compile times are a big one.

user253751
  • 57,427
  • 7
  • 48
  • 90