Gh0st
Gh0st

Reputation: 58

Sorting visualization - how to solve circular dependency?

I'm writing sorting visualization. I want it to handle events and update screen while the algorithm is running. I have a Controller class which has SortContext attribute. I want SortContext's sort method to take reference to the controller so it can use methods update and isAppRunning but I get an error:

Controller has not been declared

How can I make it work?

Controller.hpp

class Controller {

private:
  SortContext context;
  View view;
  std::vector<Sortable> data;

  bool algorithmRunning = false;

  void handleEvents();

public:
  Controller();
  void update();
  bool isAppRunning();
};

SortContext.hpp

class SortContext {

private:
  std::unique_ptr<SortStrategy> strategy;
  static const std::vector<std::function<std::unique_ptr<SortStrategy>(void)>> algorithms;

public:
  void chooseStrategy(int algorithmId);
  void sort(std::vector<Sortable> &data, Controller &controller);
};

Upvotes: 2

Views: 111

Answers (1)

anastaciu
anastaciu

Reputation: 23822

Forward declare Controller class in SortContext.hpp and include SortContext.hpp in Controller.hpp:

#include "SortContext.hpp"

class Controller {

private:
  SortContext context;
  View view;
  std::vector<Sortable> data;

  bool algorithmRunning = false;

  void handleEvents();

public:
  Controller();
  void update();
  bool isAppRunning();
};
class Controller;

class SortContext {

private:
  std::unique_ptr<SortStrategy> strategy;
  static const std::vector<std::function<std::unique_ptr<SortStrategy>(void)>> algorithms;

public:
  void chooseStrategy(int algorithmId);
  void sort(std::vector<Sortable> &data, Controller &controller);
};

Don't include SortContext.hpp where you include Controller.hpp otherwise you'll get a redefinition error:

#include "Controller.hpp"

int main()
{
    // use your classes
}

Here you can see a live demo

Upvotes: 6

Related Questions