Two classes callback without static method

Hello!
I have two classes, ClassA needs to use ClassB, but ClassB has a callback whick needs to be a static method in ClassA, but if it is static I cannot reach ClassA's variables from that method. I tried it with lambda, but I canot figure out how to use it.

ClassA.h

class ClassA
{
    private:
        void (*clickFunc)();
        
    public:
        ClassA();
		void SetCallbacks(void (*clickFunc)());
};

//-----------------------------------------------------------
ClassA.cpp

#include "ClassA.h"

ClassA::ClassA()
{
}

void ClassA::SetCallbacks(void (*clickFunc)())
{
    this->clickFunc = clickFunc;
}

void ClassA::something()
{
  clickFunc();
}

//-----------------------------------------------------------
ClassB.h

class ClassB
{
  private:
	int asd;
	ClassA button;
        void ClassB::UpClick();
    
  public:
    ClassB();
};

//-----------------------------------------------------------
ClassB.cpp
#include "ClassB.h"

ClassB::ClassB(): button()
{
  //button.SetCallbacks(UpClick); //needs to be static
  button.SetCallbacks([this](){this->UpClick();}); //got error
}

void ClassB::UpClick()
{
	this->asd = 0; //error if static
}

if you want class a to call class b then pass reference to class b to class a during class a initialisation, and then you will have class b methods available to class a

Ok, but I need two of classA in class B which needs to call separated methods.

which board are you writing for?

mega

What’s the point of having a callback tied to a member function. It needs to be static because it won’t be invoked as an instance call - just a class method call and thus won’t have access to whatever instance/member variables you might have in mind.

Just use a standard function for callback and ensure there is a way to tie that to a specific instance if needed

Is this what you are after?

class ClassB;
class ClassA
{
private:

	void(ClassB::*clickFunc)();
	ClassB* parent = nullptr;

public:
	ClassA() = delete;
	ClassA(ClassB* parent)
		: parent(parent)
	{
	}

	void SetCallback(void(ClassB::*clickFunc)())
	{
		this->clickFunc = clickFunc;
	}

	void ExecuteCallback()
	{
		if (parent)
			(parent->*clickFunc)();
	}
};

class ClassB
{
 
private:

	const char* up = "UP";
	const char* down = "DOWN";
        
public:

	ClassA button1;
	ClassA button2;

	ClassB()
		: button1{ this }, button2{ this }
	{
		button1.SetCallback(&ClassB::UpClick);
		button2.SetCallback(&ClassB::DownClick);
	}

	void UpClick() 
	{
		Serial.println(this->up);
	}

	void DownClick()
	{
		Serial.println(this->down);
	}
};

void setup() 
{
	Serial.begin(115200);
	ClassB b;
	b.button1.ExecuteCallback();
	b.button2.ExecuteCallback();
}

void loop() 
{
}

I dont think this is the best design solution tbh

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.