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

I am thinking specifically about the Strategy template (Design Patterns, GoF94), where it is proposed that the context passed to the strategy constructor can be an object that contains the strategy (as a member). But the following will not 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 Analysis data items.

This will not work because you cannot create Strategy * classes until they are defined. But its definition depends on its definition. So how should you do this? Replace SelectStrategy with

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

and execute the instance in files that # include both analyt.h and strategy.h? What is the best practice here?

+5
4

analysis.cpp strategy.h, . .

+3

/, /. (Lakos) , , :

  • Forward-declare Analysis (analysis.h strategies.h)
  • StrategyBase ( , Analysis) (strategies.h)
  • Analysis (, , ) ​​(analysis.h)
  • Analysis - (analysis.cpp)
+6
+1

++, , , . , . , .h, # include. , .h, . , , .

0

All Articles