Well @mkaes beat me to the answer, but I had slightly modified your function()
to accept a pointer to the class and not a reference.
code:
#include <iostream>
#include <thread>
class MyClass;
void function(MyClass* mc)
{
std::cout << "Friend function from thread" << std::endl;
}
class MyClass
{
public:
void init()
{
thr = std::thread(function, this);
thr.join();
// function(this);
}
friend void function(MyClass* mc);
private:
std::thread thr;
};
int main()
{
std::cout << "This is main function" << std::endl;
MyClass nc;
nc.init();
return 0;
}
Output:
This is main function
Friend function from thread
EDIT:
As per the discussion in the comments, my first code posted here had the problem that you could not call a member function or access a member variable inside the friend function()
, since the class was defined afterwards. To address that here is the alternative below. But anyways, @mkaes has already answered it in this way from the beginning.
#include <iostream>
#include <thread>
class MyClass;
void function(MyClass* mc);
class MyClass
{
public:
void init()
{
thr = std::thread(function, this);
thr.join();
// function(this);
}
friend void function(MyClass* mc)
{
std::cout << "Friend function from thread" << std::endl;
mc->test();
}
int test(){}
private:
std::thread thr;
};
int main()
{
std::cout << "This is main function" << std::endl;
MyClass nc;
nc.init();
return 0;
}