Taredon Taredon - 1 month ago 6x
C++ Question

Passing the method of an abstract class as std::function

I have some code like this (This is just a snippet, not completely valid code):

class AbstractClass {
AbstractClass() {}
virtual ~AbstractClass() {}
virtual void doA() { std::cout << "doA1\n"; };
virtual void doB() = 0;

class ImplClass : public AbstractClass {
ImplClass() {}
virtual ~ImplClass() {}
virtual void doA() override { std::cout << "doA2\n"; };
virtual void doB() override { std::cout << "doB2\n"; };

Now i would like to store a call to a member method of the AbstractClass within a std::function like this:

int main() {
AbstractClass* aClass = new ImplClass();
std::function<void()> func = std::bind(&AbstractClass::doA, *aClass)

delete aClass;
return 0;

However this does not work, according to the compiler due to the existance of pure virtual methods within AbstractClass.

Is there any solution to my problem? I haven't found one so far.


You code binds the object pointed to by aClass by value. You want to bind it by reference:

std::function<void()> func = std::bind(&AbstractClass::doA, std::ref(*aClass));

Or just bind aClass directly, pointers can be used for implicit this too:

std::function<void()> func = std::bind(&AbstractClass::doA, aClass);

[Live example]