nikomaster nikomaster - 1 month ago 14
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:

Example:

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

typedef struct
{
int(*this.func)(int);
} stah;


int main()
{
sta sa;
stah sah;

sah.func = &sa.func;

return 0;
}


it's possible this in a struct?

Answer

The declaration of func should look like this:

int(sta::*func)(int);

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:

(sa.*sah.func)(0);