0

I am writing a really simple c++ program.

#include<iostream>
#include<thread>

class Fortest{
private:
    int x;
public:
    Fortest(int a)
    {
        x=a;
    }
    void run(void)
    {
        cout<<"test sucesses!"<<endl;
    }
};

int main()
{
    Fortest  hai(1);
    std::thread  t;

    t=std::thread(std::ref(hai),&Fortest::run());
    t.join();

    cout<<"program ends"<<endl;
    return 0;
}

And I am constantly getting the error "cannot call a member function without an object". Could anyone help me to solve this problem?

msc
  • 33,420
  • 29
  • 119
  • 214
  • 1
    Possible duplicate of [Start thread with member function](https://stackoverflow.com/questions/10673585/start-thread-with-member-function) – Borgleader Oct 12 '17 at 12:22

2 Answers2

2

You have two problems:

The first is that you call the thread function, passing a pointer to the value it returns. You should pass a pointer to the function.

The second problem is that you pass the std::thread constructor arguments in the wrong order. The pointer to the function is the first argument, and the object to call it on is the second (which is the first argument to the function).

I.e. it should be something like

t = std::thread(&Fortest::run, &hai);
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
0

You are calling it the wrong way

Try:

Fortest  hai(1);
std::thread  t;

t=std::thread(&Fortest::run, std::ref(hai));
t.join();

or do so by t=std::thread(&Fortest::run, &hai); Check the arguments on std::thread

Live demo

Samer Tufail
  • 1,835
  • 15
  • 25