Error: invalid use of member when calling methods on objects in static member function

I have been getting the following error with this code:

class A {
    public:
        static void st() {
            (arr[5]->*n_st)();
        };
        void (A::*n_st)() {
            
        };
    private:
        static A *arr[10];
};

int main()
{
    return 0;
}

main.cpp: In static member function ‘static void A::st()’:
main.cpp:4:23: error: invalid use of member ‘A::n_st’ in static member function
    4 |             (arr[5]->*n_st)();
      |                       ^~~~
main.cpp:6:19: note: declared here
    6 |         void (A::*n_st)() {
      |                   ^~~~

I have laboriously looked for reasons and fixes to this error, but I cannot find similar code online. What is bugging me the most is that this code:

class A {
    public:
        static void st() {
            arr[5]->n_st();
        };
        void n_st() {
            
        };
    private:
        static A *arr[10];
};

int main()
{
    return 0;
}

Compiles flawlessly. I thought the former code would compile as well.

What am I missing here? Which sort of code would make it work? It is crucial that n_st remains of type void (A::*)().

(PS: I am a bit of a noob, still learning pointers and such, so please be patient :D).

n_st is a member variable, you have to access it through an instance:

        static void st() {
            (arr[5]->*arr[5]->n_st)();
        }

Or,

        static void st() {
            arr[5]->call_st();
        }
        void call_st() {
            (this->*n_st)();
        }

As a side note, the formatting here is quite misleading: it is equivalent to

void (A::*n_st)() = nullptr;

A pointer to member cannot have a body.
Or, to make clear that it's a variable and not a function:

        using mem_fun_t = void (A::*)();
        mem_fun_t n_st = nullptr;

wow, what a weird syntax! Thank you!

Pointers to instance functions are odd ducks. This is a good read: https://isocpp.org/wiki/faq/pointers-to-members

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.