Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using std::thread to call an overriden method from a derived class

I am trying to get something like this to work:

int main()
{
    class Base
    {
    public:
        Base() = default;
        virtual void print() = 0;
        void CallThread()
        {
            std::thread(&Base::print, *this);
        };
    };

    class derived1 : public Base
    {
    public:
        derived1() = default;
        void print() { printf("this is derived1\n"); }

    };
    class derived2 : public Base
    {
    public:
        derived2() = default;
        void print() { printf("this is derived2\n"); }

    };
    Base* ptr;
    ptr = new derived1();
    ptr->CallThread();

    return 0;
}

The result I want to happen is :

this is derived1.

The problem is it won't even compile. I am using VisualStudio 2013.

The error is :

Error 2 error C3640: 'main::Base::[thunk]: __thiscall main'::2'::Base::`vcall'{0,{flat}}' }'' : a referenced or virtual member function of a local class must be defined

Any ideas how to make this work?

edit: just to be clear, what I'm trying to do in the thread is more complicated, this is just an example of the structure of my program (so lambda isn't a good idea for me)

like image 326
Dor Ioushua Avatar asked Nov 04 '25 22:11

Dor Ioushua


1 Answers

Your code is fine, except for two things:

std::thread(&Base::print, *this);

should be:

std::thread(&Base::print, this).join(); // join & no asterisk
like image 118
Piotr Skotnicki Avatar answered Nov 07 '25 15:11

Piotr Skotnicki



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!