Question

typedef void (*callable_function)(double);
void call_function(callable_function func)
{
    func(3.0);
}

class Foo;

union converter {
    callable_function func;
    void (Foo::*foo_func)(void);
};

class Foo {
private:
    double d;
public:
    Foo(void) : d(0.0)
    {
        converter c;
        c.foo_func = &Foo::set_double;
        call_function(c.func);//I know i can call the function directly, but that is not what i want to achieve
    }

    void set_double(double value)
    {
        d = value;
    }
};

void main(void)
{
    Foo foo;
}

When trying to execute the code above, i get a heap corruption error in the line: d = value;.
Probably because the function being called is the class function, not the member function.

But if i try to change this line: c.foo_func = &Foo::set_double; to c.foo_func = &this->set_double;, i get this compiler error:

error C2276: '&' : illegal operation on bound member function expression

Question #1: Is there any way to convert the pointer(casting maybe) from void(Foo::*)(void) to void()(void) or to fix the compiler error?

Was it helpful?

Solution

pointer to "free" function and pointer to member function in C++ have different sizes. That means you technically can cast pointer to free function to void* ptr as usually they have the same size but you cannot cast member function pointer to void* or other free function - you will get what you've got.

Check this: Pointers to members representations

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top