I am working on a piece of code that represents a very strange behavior. I managed to reproduce it in a simple welcome program all over the world, here is the code:
#include <iostream>
using namespace std;
class Test
{
public:
virtual ~Test() = default;
protected:
virtual void SetUp() { }
};
class ICallbackReceiver
{
public:
virtual ~ICallbackReceiver() = default;
virtual void onReady() = 0;
};
void readyReceiver(void* userdata)
{
cout << "3) readyReceiver\n";
static_cast<ICallbackReceiver*>(userdata)->onReady();
}
using callback_t = void(*)(void*);
callback_t myCallback;
void* myUserData;
void registerCallback(callback_t callback, void* userData)
{
cout << "2) registerCallback\n";
myCallback = callback;
myUserData = userData;
}
class ConfigurableTest : public Test, public ICallbackReceiver
{
public:
void SetUp() override
{
cout << "1) ConfigurableTest::SetUp\n";
registerCallback(&readyReceiver, static_cast<void*>(this));
}
void onReady() override
{
cout << "4) ConfigurableTest::onReady\n";
}
};
int main()
{
ConfigurableTest test;
test.SetUp();
myCallback(myUserData);
return 0;
}
Whenever myCallback
called, something needs to be tested. And this is the output that should be displayed:
1) ConfigurableTest::SetUp
2) registerCallback
3) readyReceiver
4) ConfigurableTest::onReady
But, if I do not specify inheritance virtual
for the class Test
, this is the result that I see:
1) ConfigurableTest::SetUp
2) registerCallback
3) readyReceiver
1) ConfigurableTest::SetUp
2) registerCallback
As you can see, it is ConfigurableTest::onReady
never called, but ConfigurableTest::SetUp
actually called twice!
What is the origin of this behavior? How can I rebuild the code to reproduce the correct behavior without using virtual
inheritance?
source
share