How to call static function, member function by reference, value and pointer in thread.

It is very simple to call a member function or static member function from thread following is the example the shall help us.

For best understanding please COPYPASTE and RUN in any online compiler.

include <iostream>
#include <thread>
#include <string>
using namespace std;

class Suggest
    string m_name;
    void updateName(string str)
    void displayName()
        cout<<"Name "<<m_name<<endl;
    static void display(string str)
        cout<<"Static Function Call :: "<<str<<endl;
int main()
    //Call static function both ways are correct
    std::thread objThd(Suggest::display,"without &");

    std::thread objThd1(&Suggest::display,"with &");

    cout<<endl<<"Call Member Function "<<endl;
   //call thread by object for member function,
   //object is passed by value

    Suggest sObj;
    cout<<"Object PASSED-BY-VALUE "<<endl;

    std::thread objThrd(&Suggest::updateName,sObj,"Value - Suggestion");

    //object is passed by reference
    cout<<endl<<"Object PASSED-BY-REFERENCE "<<endl;
    Suggest sObjNew;

    std::thread objThrd1(&Suggest::updateName,&sObjNew,"Reference - Suggestion");

    //object is passed by pointer
    cout<<endl<<"Object PASSED-BY-POINTER "<<endl;
    Suggest* ptrObj=new Suggest;

    std::thread objThrd2(&Suggest::updateName,ptrObj,"Pointer - Suggestion");
    return 0;


Compile: g++ classFunctions.cpp -o  classFunctions -lpthread

Output: $ ./classFunctions

Static Function Call :: without &
Static Function Call :: with &

Call Member Function


Name Tech
Name Tech


Name Tech
Name Reference - Suggestion


Name Tech
Name Pointer - Suggestion

PREV:: How to Call function with Reference Variable, 
Default Argument and Pointer Variable from thread.

Your Comments /Suggestions & Questions are always welcome. 

We would like to help you with best of our knowledge.

So feel free to put Questions

No comments:

Post a Comment