Case where the problem occours
Please consider the following c++ code:
#include
#include
#inclu
This is just object slicing. Pass the instance by reference:
auto func = std::bind(&print, std::ref(instance));
// ^^^^^^^^
To explain this a bit more: Like most C++ standard library types, the result type of a bind
expression owns all its bound state. This means you can take this value and pass it around freely and store it and come back to it later in a different context, and you can still call it with all its bound state ready for action.
Therefore, in your code, the bind object was constructed with a copy of instance
. But since instance
wasn't a complete object, you caused slicing to happen.
By contrast, my code copies a std::reference_wrapper<A>
into the bind object, and that's essentially a pointer. It doesn't own the instance object, so I need to keep it alive as long as the bind object may get called, but it means that the bound call is dispatched polymorphically to the complete object.