Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assignment of function pointers (effective c++ item 35) [duplicate]

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 ?

like image 790
Sean Ian Avatar asked Jul 26 '18 19:07

Sean Ian


1 Answers

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.

like image 111
Tim Randall Avatar answered Oct 02 '22 09:10

Tim Randall