Home >Backend Development >C++ >How Can I Correctly Pass Member Function Pointers in C ?

How Can I Correctly Pass Member Function Pointers in C ?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-05 08:52:10282browse

How Can I Correctly Pass Member Function Pointers in C  ?

Passing Member Function Pointers in C

In object-oriented programming, it is often necessary to pass a member function as an argument to another function. However, doing this correctly can be a bit tricky, especially when using the this pointer.

Let's consider a specific example from the code snippet provided:

class testMenu : public MenuScreen {
  // ...
  void test2() {
    draw = true;
  }
};

MenuButton<testMenu> x;

testMenu() : MenuScreen("testMenu") {
  x.SetButton(100, 100, ..., &test2);
}

Here, the test2 member function is assigned to the ButtonFunc member of the MenuButton using the SetButton function:

template <class object>
void MenuButton::SetButton(..., void (object::*ButtonFunc)()) {
  this->ButtonFunc = &ButtonFunc;
}

The problem arises when calling the test2 function from the MenuButton class. To do this, we need both a pointer to the object (i.e., testMenu) and a pointer to the function (i.e., &test2). In the modified version of SetButton:

template <class object>
void MenuButton::SetButton(..., object *ButtonObj, void (object::*ButtonFunc)()) {
  this->ButtonObj = ButtonObj;
  this->ButtonFunc = ButtonFunc;
}

We pass a reference to the object, which can be accessed using the ButtonObj pointer. The member function pointer is then invoked using ((ButtonObj)->*(ButtonFunc))().

Finally, the corrected testMenu constructor:

testMenu() : MenuScreen("testMenu") {
  x.SetButton(100, 100, ..., this, &test2);
}

The above is the detailed content of How Can I Correctly Pass Member Function Pointers in C ?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn