how to get a pointer to a struct's function

1
2
3
4
5
6
7
8
9
10
11
struct X{
	int x = 3;
	int get_x(){return x;}
	int add_x(int i){return x+i;}
};

int main() {
	X str;
	int (*fcnPtr)(){&(str.get_x)};//this line does not work
	std::cout << fcnPtr(2) << std::endl;
}
Last edited on
AFAIK, you can't get a pointer to a bound member function.

You can do this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
struct X {
	int x = 3;
	int get_x() { return x; }
	int add_x(int i) { return x + i; }
};

int main()
{
	int (X:: *pf)() = &X::get_x;

	X str;

	std::cout << (str.*pf)() << '\n';
}

Every instance of a struct shares the exact same class functions, so you just need a pointer to the class function.

That said, you almost certainly don't really need it. If you're doing this for anything other than just to see what it does, you probably should be doing something else instead.
Last edited on
The C-ish way using function pointers.
https://www.newty.de/fpt/callback.html#member

The C++ way using std::function
https://en.cppreference.com/w/cpp/utility/functional/function
Topic archived. No new replies allowed.