Search code examples
c++includedependenciesstrategy-pattern

How do you pass 'this' as an argument to another class constructor without circular dependencies?


I'm thinking specifically of the Strategy pattern (Design Patterns, GoF94), where it is suggested that the context passed to the strategy constructor can be the object which contains the strategy (as a member) itself. But the following won't work:

//analysis.h

class StrategyBase;
class Strategy1;
class Strategy2;
class Analysis
{
   ...
      void ChooseStrategy();
   private:
      StrategyBase* _s;
      ...
};

//analysis.cpp

void Analysis::ChooseStrategy()
{
   if (...) _s = new Strategy1(this);
   else if (...) _s = new Strategy2(this);
   ...
}

//strategy.h

#include analysis.h
...

and then StrategyBase and its subclasses then access the data members of Analysis.

This won't work because you can't instantiate Strategy* classes before they've been defined. But its definition depends on that of Analysis. So how are you supposed to do this? Replace ChooseStrategy with

void SetStrategy(StrategyBase* s) { _s = s; }

and do the instantiation in files which #include both analysis.h and strategy.h? What's best practice here?


Solution

  • analysis.cpp also needs to include strategy.h to pick up the full definitions of the strategies. Since it's a source file there's no circular dependency.