0

Similar to this question: Start thread with member function and this one: std::thread calling method of class

However I have the following:

#include <thread> #include <iostream> class myAbstractClass { public: virtual void myFunction() = 0;//abstract class } class myFirstClass : public myAbstractClass { public: void myFunction() { std::cout << "First class here";} } class mySecondClass : public myAbstractClass { public: void myFunction() { std::cout << "Second class here";} } 

Then I have to call myFunction() from a different place in a new thread, but the following does not compile (and I can't think of anything else to try):

public void callMemberFunctionInThread(myAbstractClass& myInstance) { std::thread myThread (&myAbstractClass::myFunction, myInstance); //supposed to call myInstance.myFunction() on myThread } 
8
  • 1
    "does not compile" isn't very specific. What error messages are you getting? Commented Apr 9, 2017 at 14:15
  • Intellisense doesn't complain, compilation starts and then it gives C2259 'myAbstractClass': cannot instantiate abstract class in file tuple located in C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.10.25017\include (line 199) Commented Apr 9, 2017 at 14:24
  • 1
    std::ref(myInstance)? Commented Apr 9, 2017 at 14:25
  • Please fix your program so that it is an minimal reproducible example first. Lots of trivial syntax error here. Commented Apr 9, 2017 at 14:25
  • The abstract class member function should be virtual if the derived classes are supposed to override it. Don't know if that works with std::thread anyway. Commented Apr 9, 2017 at 14:42

1 Answer 1

1

Pass std::ref(myInstance). Note that std::thread constructor will make a copy of the arguments passed to it (see here), and you can't copy a myAbstractClass.

(Then, all of this will still work because std::thread functionality is described in terms of std::invoke, which unwraps the std::reference_wrapper obtained by std::ref and calls the pointer to member function onto it. See here).

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.