Creating a thread to a class object
I have the class object Chat *p, and I'm looking to run the method Foo(int num) on it (usually running by p -> Foo(3) for example). I've written this code :
std::thread F(&Chat::Foo, 4);
though, it does not compile to me, and I also see theres an error, since I was not able to put p -> Foo into it (instead of &Chat::Foo...)
How can I run this code correctly?
The answer from how object methods actually work. When you call p->foo(3) what the compiler translates it to, roughly speaking, is Chat::foo(p, 3). P is always passed as a hidden parameter in any call to a function. C++ doesn't show you this and you can't actually call Chat::foo(p, 3), this just isn't allowed, but it roughly how things work in reality.
The variable this that is available in any member function is just the address that is passed in as the hidden first parameter and any member variables that you access in the function reference the hidden first parameter. So... what you need to do in order to call any member function as the starting point to a thread, is pass the pointer to the object as it's first parameter. std::thread F(&Chat::Foo, p, 4); will, I believe, start the thread properly.