Home >Backend Development >C++ >How to Correctly Call Pointers to Member Functions in C ?

How to Correctly Call Pointers to Member Functions in C ?

Susan Sarandon
Susan SarandonOriginal
2024-12-31 13:20:11579browse

How to Correctly Call Pointers to Member Functions in C  ?

Calling Pointers to Member Functions in C

Pointers to member functions provide a convenient way to store and execute specific member functions while offering flexibility in dynamic binding. However, calling these function pointers has its unique syntax.

With non-static member functions, calling a function pointer requires providing both named parameters and a this pointer, which represents the object on which the function will be invoked. The following corrected code demonstrates the correct syntax:

typedef void (Box::*HitTest)(int x, int y, int w, int h);

for (std::list::<HitTest>::const_iterator i = hitTestList.begin(); i != hitTestList.end(); ++i)
{
    HitTest h = *i;
    (box->*h)(xPos, yPos, width, height);
}

Here, box is a pointer to the Box object that will function as the this pointer. By using box->*h, we are essentially calling the member function h on the specific Box instance pointed to by box.

Regarding adding member functions to the list, the corrected code would be:

std::list<HitTest> list;

for (std::list<Box*>::const_iterator i = boxList.begin(); i != boxList.end(); ++i)
{
    Box* box = *i;
    list.push_back(&Box::HitTest);
}

The above is the detailed content of How to Correctly Call Pointers to Member Functions 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