1

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.

3 Answers 3

0

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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..

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.