Pass a function pointer to a class object

Viewed 153

I need to be able to specify a function for a class to be able to run (a callback function?) as part of a menu system, my knowledge of c++ is stretched here. Obviously this won't compile but hopefully it gives an idea of what I'm trying to do -

void testFunc(byte option) {
  Serial.print("Hello the option is: ");
  Serial.println(option);
}

typedef void (*GeneralFunction)(byte para);
GeneralFunction p_testFunc = testFunc;

class testClass {
    GeneralFunction *functionName;
  public:
    void doFunction() {
      functionName;
    }
};

testClass test { *p_testFunc(123) };

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

void loop() {
 
}

I am aware of some std:: options but Arduino doesn't have them implemented unfortunately.

Edit: The compiler output for this code -

sketch_mar10a:17:29: error: void value not ignored as it ought to be

 testClass test { *p_testFunc(123) };

                             ^

sketch_mar10a:17:35: error: no matching function for call to 'testClass::testClass(<brace-enclosed initializer list>)'

 testClass test { *p_testFunc(123) };

                                   ^
2 Answers

Please find the below code, see if this helps,you need a constructer to take the parameter, also you can't call the function from the parameter list while its expecting a function pointer

#include <iostream>

using namespace std;

void testFunc(int option) {
  std::cout<<"in fn "<<option;
}

typedef void (*GeneralFunction)(int para);
GeneralFunction p_testFunc = testFunc;

class testClass {
    GeneralFunction functionName;
    int param1;
  public:
    testClass(GeneralFunction fn,int par1):functionName(fn),param1(par1){}
    void doFunction() {
      functionName(param1);
    }
};

testClass test (p_testFunc,123);

void setup() {
  test.doFunction();
}

void loop() {

}


int main()
{
    setup();
    return 0;
}

Thanks to Bibin I have adapted his code to suit Arduino, separated the constructor, and initialized the class in setup().

void testFunc(byte option) {
  Serial.print("Hello the option is: ");
  Serial.println(option);
}

typedef void (*GeneralFunction)(byte para);
GeneralFunction p_testFunc = testFunc;

class testClass {
    GeneralFunction functionName;
    byte param1;
  public:
    testClass(GeneralFunction fn, int par1);
    void doFunction() {
      functionName(param1);
    }
};

void setup() {
  Serial.begin(9600);
  testClass test (p_testFunc, 123);
  test.doFunction();
}

void loop() {
}

testClass::testClass(GeneralFunction fn, int par1)  //constructor
  : functionName(fn), param1(par1) {}

Which outputs:

Hello the option is: 123
Related