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
Release: 2024-12-05 08:52:10
Original
273 people have browsed it

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);
}
Copy after login

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;
}
Copy after login

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;
}
Copy after login

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);
}
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template