Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Function pointer
(section)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
== In C++ == In C++, in addition to the method used in C, it is also possible to use the C++ standard library class template {{mono|std::function}}, of which the instances are function objects: <syntaxhighlight lang="cpp"> #include <iostream> #include <functional> using namespace std; static double derivative(const function<double(double)> &f, double x0, double eps) { double eps2 = eps / 2; double lo = x0 - eps2; double hi = x0 + eps2; return (f(hi) - f(lo)) / eps; } static double f(double x) { return x * x; } int main() { double x = 1; cout << "d/dx(x ^ 2) [@ x = " << x << "] = " << derivative(f, x, 1e-5) << endl; return 0; } </syntaxhighlight> === Pointers to member functions in C++ === {{See also|#Alternate C and C++ syntax}} This is how C++ uses function pointers when dealing with member functions of classes or structs. These are invoked using an object pointer or a this call. They are type safe in that you can only call members of that class (or derivatives) using a pointer of that type. This example also demonstrates the use of a typedef for the pointer to member function added for simplicity. Function pointers to static member functions are done in the traditional 'C' style because there is no object pointer for this call required. <syntaxhighlight lang="cpp"> #include <iostream> using namespace std; class Foo { public: int add(int i, int j) { return i+j; } int mult(int i, int j) { return i*j; } static int negate(int i) { return -i; } }; int bar1(int i, int j, Foo* pFoo, int(Foo::*pfn)(int,int)) { return (pFoo->*pfn)(i,j); } typedef int(Foo::*Foo_pfn)(int,int); int bar2(int i, int j, Foo* pFoo, Foo_pfn pfn) { return (pFoo->*pfn)(i,j); } typedef auto(*PFN)(int) -> int; // C++ only, same as: typedef int(*PFN)(int); int bar3(int i, PFN pfn) { return pfn(i); } int main() { Foo foo; cout << "Foo::add(2,4) = " << bar1(2,4, &foo, &Foo::add) << endl; cout << "Foo::mult(3,5) = " << bar2(3,5, &foo, &Foo::mult) << endl; cout << "Foo::negate(6) = " << bar3(6, &Foo::negate) << endl; return 0; } </syntaxhighlight>
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)