2

I'm learning c++ and have faced a weird error (see title). Inside class instance I'm trying to call another function from that class while adding it to a vector of threads. This is my sample code:

file: header.h

class MyClass{
    void threaded_func();
    bool main_func();
};

file: main.cpp

#include <thread>
#include <vector>
#include "header.h"

using namespace std;

vector<thread> threads;

void MyClass::threaded_func()
{
    cout << "I'm threaded_func\n";
}

bool MyClass::main_func()
{
    vector<thread> threads;
    threads.push_back(thread(threaded_func));

    return true;
}

int main()
{
    MyClass mc;
    return 0;
}

This returns me an error reference to non-static member function must be called. I've checked this question, however it didn't help me (replacing thread(threaded_func) with thread(MyClass::*threaded_func)). I also tried to use this keyword to tell compilator I'm using the same class member to invoke method, but seems that my C++ knowledge is simply too low to solve this problem.

Are there any workarounds? I've also looked through this question, however it is about variables, not functions.

Groosha
  • 2,897
  • 2
  • 22
  • 38
  • 2
    If the goal is to create a thread that run `threaded_func` on the current object, then the thread has to have two arguments: the function to call, and the argument. `thread(&MyClass::threaded_func, this)`. But if you're struggling with fundamental syntax issues you probably shouldn't be writing multi-threaded code yet. – Pete Becker Jul 23 '18 at 11:44
  • @PeteBecker I'm making a pool of threads which are doing _something_. Could you please point me to these "fundamental syntax issues" which I don't see here? – Groosha Jul 23 '18 at 11:46
  • 1
    The fundamental syntax issue here is that you're trying to pass a member function by giving its unqualified name. I showed you the correct syntax. – Pete Becker Jul 23 '18 at 11:48
  • @PeteBecker edit: Sorry, you're right. Thanks (edited this comment since I had a bug) – Groosha Jul 23 '18 at 11:55

0 Answers0