Search code examples
c++function-pointerseffective-c++

Assignment of function pointers (effective c++ item 35)


In effective c++, item 35, the author introduces the strategy pattern via function pointers. Specifically on page 172

class GameCharacter; 
int defaultHealthCalc(const GameCharacter& gc);
class GameCharacter {
public:
  typedef int (*HealthCalcFunc)(const GameCharacter&);
  explicit GameCharacter(HealthCalcFunc hcf = defaultHealthCalc)//why not &defaultHealthCalc?
  : healthFunc(hcf)
  {}
  int healthValue() const
  { return healthFunc(*this); }
  ...
private:
  HealthCalcFunc healthFunc;
};

On the sixth line, why the assignment to the function pointer HealthCalcFunc is defaultHealthCalc instead of &defaultHealthCalc ?


Solution

  • Since the compiler knows that you are assigning a value to a pointer-to-function, it is enough to specify the name of the function you want -- the syntax is unambiguous.

    If you wanted to add the ampersand to make it clear, the syntax allows that, but it isn't necessary.

    Similarly, when calling a function from a pointer, you can either use the name of the pointer directly (as is done in the example code), or explicitly dereference it using the '*' operator. The compiler knows what you mean in either case.