DEV Community

Cover image for Bug of the week #11
pikoTutorial
pikoTutorial

Posted on • Originally published at pikotutorial.com

Bug of the week #11

Welcome to the next pikoTutorial!

The error we're handling today is a C++ compilation error:

invalid use of non-static member function
Enter fullscreen mode Exit fullscreen mode

What does it mean?

It often occurs when the compiler encounters a place in the code where it would normally expect a static member function, but the actual function is not static. Let's say for example, that we have a function which takes a function pointer to some other function and calls it:

void RunFunction(void (*func)())
{
    func();
}
Enter fullscreen mode Exit fullscreen mode

If you create a SomeClass class with a non-static Run function and try to pass it to the RunFunction function using the range operator like below:

struct SomeClass
{
    void Run()
    {
        std::cout << "Running..." << std::endl;
    }
};

int main()
{
    RunFunction(SomeClass::Run);
}
Enter fullscreen mode Exit fullscreen mode

the compiler will throw an error:

error: invalid use of non-static member function ‘void SomeClass::Run()’
Enter fullscreen mode Exit fullscreen mode

How to fix it?

The easiest way is to just make Run function static, by adding static keyword to its definition:

static void Run()
Enter fullscreen mode Exit fullscreen mode

However, if you can't make that function static, you would have to adjust the RunFunction function to accept some callable object instead of a raw function pointer:

void RunFunction(std::function<void()> func)
{
    func();
}
Enter fullscreen mode Exit fullscreen mode

And bind SomeClass::Run function to a specific object instance using std::bind:

SomeClass instance;
RunFunction(std::bind(&SomeClass::Run, instance));
Enter fullscreen mode Exit fullscreen mode

Or a simple lambda:

SomeClass instance;
RunFunction([&instance]{ instance.Run(); });
Enter fullscreen mode Exit fullscreen mode

Top comments (0)