Search code examples
c++multithreadingvirtual-functionspure-virtual

Call a derived member function from parent class


I need to call B::f() in the thread member function. What I get is "pure virtual method called". How can I do this?

I assume all this happens because of &A::thread_f in the A initializer list where I explicitly name a scope.

class A {
protected:
    std::thread _thread;

    A() : _thread(&A::thread_f, this) { }

    ~A() { 
        _thread.join();
    }

    virtual void f() = 0;

    void thread_f() {
        f();
    }
};

class B : public A {
protected:
    void f() override {
        std::cout << "B::f()" << std::endl;
    }
};

Solution

  • as @Evg says, by starting a thread,A ctor call member function f of B before constructing B.

    The solution is to start thread after B is constructed.

    #include<iostream>
    #include<vector>
    #include <stdlib.h>
    #include <thread>
    
    using namespace std;
    class A {
    public:
        ~A() {
            _thread.join();
        }
        void start()
        {
            _thread = std::thread(&A::thread_f, this);
        }
    protected:
        std::thread _thread;
        A()
        {
        }
    
        virtual void f() = 0;
        void thread_f() {
            f();
        }
    };
    
        class B : public A {
        protected:
            void f() override
            {
                std::cout << "B::f()" << std::endl;
            }
        };
    
    void main() {
        A *pA=new B;
        pA->start();
        delete pA;
    }