Odd behavior without virtual inheritance

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;
};

// C-style callback
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 /*virtual*/ 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 myCallbackcalled, 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 virtualfor 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::onReadynever called, but ConfigurableTest::SetUpactually called twice!

What is the origin of this behavior? How can I rebuild the code to reproduce the correct behavior without using virtualinheritance?

+4
source share
1

, ConfigurableTestvoid *ICallbackReceiver, . ConfigurableTest void * - .

. : void *

+4

Source: https://habr.com/ru/post/1691196/


All Articles