In Effective C++, 3rd Edition, Page 173~175, Scott Meyers talked of alternatives to virtual functions using the strategy pattern:
class GameCharacter;
int defaultHealthCalc(const GameCharacter& gc);
class GameCharacter {
public:
typedef std::tr1::function<int (const GameCharacter&)> HealthCalcFunc;
explicit GameCharacter(HealthCalcFUnc hcf = defaultHealthCalc)
: healthFunc(hcf)
{}
int healthValue const
{ return healthFunc(*this) }
...
private:
HealthCalcFunc healthFunc;
};
...
struct HealthCalculator {
int operator()(const GameCharacter&) const
{ ... }
};
...
class EyeCandyCharacter: public GameCharacter {
explicit EyeCandyCharacter(HealthCalcFunc hcf=defaultHealthCalc)
:GameCharacter(hcf)
{ ... }
...
}
...
EyeCcandyCharacter ecc(HealthCalculator());
The last statement is to illustrate how to use a health calculation function object in the constructor of EyeCandyCharacter class.
My question is, the constructor of EyeCandyCharacter class requires some function that takes a parameter compatible with a const GameCharacter& and returns something convertible to an int.
Is this supported/implemented by operator() defined in struct HealthCalculator? I don't quite understand the meaning of this overloaded operator here.
Another question of mine here is that the initializer list in the constructor of the derived class usually only initializes the data members of itself (though I know the base part of the derived class is also intialized implicitly). How come the base class GameCharacter appears in the initializer of derived class EyeCandyCharacter?