nikomaster nikomaster - 8 months ago 88
C++ Question

struct pointer function points to other function of other struct

I was wondering if is possible to point a function of other structure into of a structure:


typedef struct
int func(int z)
return z * 2;
} sta;

typedef struct
} stah;

int main()
sta sa;
stah sah;

sah.func = &sa.func;

return 0;

it's possible this in a struct?


The declaration of func should look like this:


Or, alternatively:

using my_type = int(sta::*)(int);
my_type func;

This is easier to read: my_type is an alias for the type pointer to a member function of sta that gets an int and returns an int.
func is nothing more that a data member having type my_type.

In order to assign an actual pointer to member function to func, you can do this instead:

sah.func = &sta::func;

You can then invoke it as it follows: