4 years, 10 months ago.

How to attach one class's method to object of another class

Dear friends, I need your help. I have two classes: "Button". "Encoder". Encoder class contains a member of Button type. Button class has some event that executes some function located in clickFunc variable and and a funciotn attachClick to write this variable. I'm trying to attach one of Encoder's method to Button's object with the help of Callback class and get ting a error message. Can you please tell me how to do this correct?

include the mbed library with this snippet

#include <mbed.h>

//callback function declaration
typedef void (*callbackFunction)(void);

class Button
{
    callbackFunction clickFunc;
public:
    void attachClick(callbackFunction newFunction);
} btn;

void Button::attachClick(callbackFunction newFunction)
{
    clickFunc = newFunction;
};

class Encoder
{   
    //a member of "Encoder" class
    Button sw;
    void swFunction (void);
public:
    //Constructor
    Encoder();
} enc;

void Encoder::swFunction (void){
    //doing something;    
};

Encoder::Encoder(){
    sw.attachClick(callback(this, &Encoder::swFunction)); //Here is a problem...   
};


int main()
{

    while (true) {
    }
}

1 Answer

4 years, 10 months ago.

Hello Alexander,

You can try something like:

#include <mbed.h>

//callback function declaration
//typedef void (*callbackFunction)(void);  // Recplaced by "Callback<void ()>"

class Button
{
    Callback<void ()>   clickFunc;
public:
    void attachClick(Callback<void ()> newFunction);
} btn;

void Button::attachClick(Callback<void ()> newFunction)
{
    clickFunc = newFunction;
};

class Encoder
{
    //a member of "Encoder" class
    Button  sw;
    void    swFunction(void);
public:
    //Constructor
    Encoder();
} enc;

void Encoder::swFunction(void)
{
    //doing something;
};

Encoder::Encoder()
{
    sw.attachClick(callback(this, &Encoder::swFunction));
};

int main()
{
    while (true) { }
}

Accepted Answer

Thanks, Zoltan. Your code does not generate any error message. But I need time to understand how it works :)

posted by Alexander Urezchenko 15 Jun 2019