Evans Belloeil
Evans Belloeil

Reputation: 2503

Static function and access to the class variable

I've got a class MainWindow that contain a static function lancerServeur() ( this function is static because I use it in a thread ), now I want to call a private variable bool_Serveur_Fonctionne in this function, here's the code :

void MainWindow::lancerServeur(){
    serveur s;
    while(bool_Serveur_Fonctionne){
        s.receiveDataUDP();
    }
}

Unfortunately I can't, after some research it seems like a static function can't have access to what is not static, so what do I do to permit my function to access to : bool_Serveur_Fonctionne ? And could you give more information about this, what if I want to change this variable in static function and non-static function ?

Here's the error : invalid use of member 'MainWindow::bool_Serveur_Fonctionne' in static member function bool bool_Serveur_Fonctionne;

Thanks for your help.

Upvotes: 0

Views: 4856

Answers (3)

Nishant Kumar
Nishant Kumar

Reputation: 2179

you can pass it as parameter to thread function:

void MainWindow::lancerServeur(MainWindow& obj){
    serveur s;
    // IF bool_Serveur_Fonctionne is public otherwise use some function to 
    //return value of this
    while(obj.bool_Serveur_Fonctionne){
        s.receiveDataUDP();
    }
}

int main(int argc, char* argv[]){
    MainWindow m; 
    std::thread t(MainWindow::lancerServeur, std::ref(m));
    t.join();  
}

EDIT:

Updated the code as @Casey has suggested.

Upvotes: 1

Sander De Dycker
Sander De Dycker

Reputation: 16243

this function is static because I use it in a thread

You can start a thread with a non-static member function :

std::thread(&MainWindow::lancerServeur, mainWindowInstance);

Upvotes: 2

quantdev
quantdev

Reputation: 23813

static functions can only access static members of a class, they don't have access to this pointer. If you think about it, a static method is not attached to any instance of an object, so it makes no sense to try to access a non-static member (you would need an instance of an object to do that).

You have three choices :

1) Make bool_Serveur_Fonctionne a static member of the class.

2) Pass an instance of an object (MainWindow) with an accessor tobool_Serveur_Fonctionne to your static method.

3) Pass a reference of bool_Serveur_Fonctionne as a parameter of your static method.

Note:

Consider std::atomic<bool> as the type for your bool_Serveur_Fonctionne

Upvotes: 3

Related Questions