Question

This is a follow up question to my previous post: C++: Initializing Struct and Setting Function Pointer

My new question is how do I call a pointer-to-member function within a struct? I have modified my previous code to:

float MyClass::tester(float v){
    return 2.0f*v;
}

struct MyClass::Example{
    float(Scene_7::*MyFunc)(float);

    float DoSomething(float a){
        return (MyFunc)(a);           //ERROR, SEE BELOW FOR OUTPUT
    }
};

I then set the function as follows, and output the result to the call:

struct Example e;
e.MyFunc = &MyClass::tester;
std::cerr << e.DoSomething(1.0f) << std::endl;

I get the following error: must use '.' or '->' to call pointer-to-member function...

The problem is I don't know how to do this. I am guessing I have to call something like this->*(myFunc)(a) within DoSomething but this references the struct. I have tried searching "this within struct pointer-to-member function" but have not been able to find anything. Any help or suggestions would be great. I feel like I am close but it is just a matter of syntax at this point.

Was it helpful?

Solution

The operator precedence of .* and ->* is, IMHO, broken. You need to wrap the operands in parentheses in order to call.

return (this->*MyFunc)(a);

Otherwise, the compiler thinks you're doing this->*(MyFunc(a)), which is obviously invalid.

Interestingly enough, (this->*MyFunc) as a standalone expression is also invalid. It needs to be called on the spot.

OTHER TIPS

I cant tell if you have other errors, do to the lack of code, but you are calling a member function the wrong way, you call them like this:

return (obj->*MyFunc)(6);

I am not sure if you can use this in place of obj on the line above, since from the declaration, you need a pointer to an object of type Scene_7, so you will need to know a pointer of the correct type at that spot in the code..

Remember that . operator has higher precedence than the * operator. So when dealing with pointes and structs etc you will need to use paranthesis or -> operator which means that the pointer points to what.

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