Pages: [1]   Go Down
Author Topic: Passing a function to a constructor  (Read 687 times)
0 Members and 1 Guest are viewing this topic.
0
Offline Offline
Newbie
*
Karma: 0
Posts: 22
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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
Logged

Mountain View, CA
Offline Offline
Newbie
*
Karma: 0
Posts: 20
Professional C/C++ programmer available for projects
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

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

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

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

private:
  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.

« Last Edit: June 29, 2011, 09:19:21 pm by montecito » Logged

Florida
Offline Offline
Sr. Member
****
Karma: 4
Posts: 431
hookedup!
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

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

Code:

class HasCallback {

public:

  void (*cmdCallback)(int action);

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

  ~HasCallback() {
  };

  void testCallack(int testAction){
    cmdCallback(testAction);
  }


};


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


void setup(){
  Serial.begin(9600);
}

int currentAction = 0;

void loop(){
  currentAction++;
  if (currentAction > 10000){
     currentAction = 1;
  }
 
  hc.testCallack(currentAction);
  delay(100);
 
}
« Last Edit: June 29, 2011, 09:40:46 pm by marklar » Logged

0
Offline Offline
Newbie
*
Karma: 0
Posts: 22
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Thank you both. The information has been most helpful.

Ed
Logged

Pages: [1]   Go Up
Jump to: