-1

I am getting compile error C2064 for this code.

class MainClass;

class MyClass
{
public:
    MyClass();
    void (MainClass::*functionPointer)();
    void callback();
};

class MainClass
{
public:
    void testFunction();
    void setup();
    MyClass myClass;
};

void MainClass::testFunction()
{
}

void MainClass::setup()
{
    myClass.functionPointer = &MainClass::testFunction;
    myClass.callback();
}

void MyClass::callback()
{
    functionPointer();
};

int main() {
    MainClass mainClass;
    mainClass.setup();
    return(0);
}

I have tried:

  • Changing the function call syntax to this->functionPointer();
  • Explicitly casting functionPointer to a regular function pointer with the code: void (*fp)(void) = (void (*)(void))this->functionPointer; fp();
9
  • 1
    Does this answer your question? Pointer-to-member-function error Commented Jul 18, 2023 at 14:28
  • 1
    What error are you getting? Commented Jul 18, 2023 at 14:28
  • 2
    You need an instance of MainClass to call the functionPointer with. Your MyClass does not have access to any such instance in the current code Commented Jul 18, 2023 at 14:29
  • 1
    I have tried: -- Before embarking on using pointers to non-static member functions, make sure you know how to use them. C++ is not the type of computer language where guessing will work. Commented Jul 18, 2023 at 14:31
  • What is C2064? This is not a standard error. Commented Jul 18, 2023 at 14:38

1 Answer 1

2

Not sure what you are trying to achieve, but member function pointers don't work in the way that you are trying to use them. In order to call a member function via a member function pointer you need an instance of the type that the member function is part of.

With the following code changes your code should work, not sure if this is what you want or not however.

void MainClass::setup()
{
    myClass.functionPointer = &MainClass::testFunction;
    myClass.callback(*this); // pass instance of MainClass to callback
}

void MyClass::callback(MainClass& mc)
{
    (mc.*functionPointer)(); // use passed instance to call member function
}

The .* operator is the way you call a member function using an object instance and member function pointer. There is a similar ->* operator that takes and object pointer and member function pointer.

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

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.