Passing a function to a constructor

Hi All, I am writing a library to support the 74C923, a chip that manages a 4X5 keypad. (I will post the library on the playground once completed) It's working well in its present form, but what I would like to do is to be able to pass a function to the class constructor and have the class remember the function throughout the program's running. This would be similar to the attachInterrupt() routine. The user would write the function that would handle key presses; the rest of the housekeeping would be handled by the chip and the class.

I've researched this a bunch and am having difficulty with the code. I think I understand how to pass a function as a parameter to another function, but I don't know how to store the address in a variable in the class. Or can't I do that at all?

Appreciate any help offered.

Thanks. Ed Ringel

You can pass a function pointer to a constructor, store it, and call it like this:

class foo {
  foo(int (*p)(int)) : _p(p) { }

  int doit(val) {
    return _p(val);

  int (*_p)(int);

int doubleit(int val) { 
  return val*2;

int main() {
  foo f(doubleit);
  int result = f.doit(2);


You will need to adapt to the particular signature of the function you wish to store. But this gives the basic syntax and paradigm.

Someone beat me to the post but since I created a working example, here it is.

class HasCallback {


  void (*cmdCallback)(int action);

  HasCallback(void (*cmd)(int cmd)) {
    this->cmdCallback = cmd;

  ~HasCallback() {

  void testCallack(int testAction){


void demoCallback(int action){
   Serial.println(action, DEC); 
HasCallback hc = HasCallback(&demoCallback);

void setup(){

int currentAction = 0;

void loop(){
  if (currentAction > 10000){
     currentAction = 1;

Thank you both. The information has been most helpful.