Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call a pointer-to-function outside the structure

I have a structure, inside it a pointer to function from the same structure. And now I need to call a pointer to function outside the structure. I give an example of the code below:

#include <iostream>

struct test {
    void (test::*tp)(); // I need to call this pointer-to-function
    void t() {
        std::cout << "test\n";
    }
    void init() {
        tp = &test::t;
    }
    void print() {
        (this->*tp)();
    }
};
void (test::*tp)();

int main() {
    test t;
    t.init();
    t.print();
    (t.*tp)(); // segfault, I need to call it
    return 0;
}
like image 296
John Doe Avatar asked Aug 25 '26 13:08

John Doe


1 Answers

(t.*tp)(); is trying to invoke the member function pointer tp which is defined at global namespace as void (test::*tp)();, note that it's initialized as null pointer in fact (via zero initialization1), invoking it leads to UB, anything is possible.

If you want to invoke the data member tp of t (i.e., t.tp) on the object t, you should change it to

(t.*(t.tp))();
     ^
     |
     ---- object on which the member function pointed by tp is called

If you do want to invoke the global tp, you should initialize it appropriately, such as

void (test::*tp)() = &test::t;

then you can

(t.*tp)(); // invoke global tp on the object t

1 About zero initialization

Zero initialization is performed in the following situations:

1) For every named variable with static or thread-local storage duration that is not subject to constant initialization (since C++14), before any other initialization.

like image 152
songyuanyao Avatar answered Aug 27 '26 04:08

songyuanyao



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!