Wikibooks: C++ Programming/Operators/Pointers/To Functions

= Pointers to functions = The [[pointers]] we have looked at so far have all been data pointers pointers to functions (more often called function pointers) are very similar and share the same characteristics of other pointers but in place of pointing to a variable they point to functions. Creating a...

Full description

Bibliographic Details
Format: Book
Language:English
Subjects:
Online Access:https://en.wikibooks.org/wiki/C%2B%2B_Programming/Operators/Pointers/To_Functions
Description
Summary:= Pointers to functions = The [[pointers]] we have looked at so far have all been data pointers pointers to functions (more often called function pointers) are very similar and share the same characteristics of other pointers but in place of pointing to a variable they point to functions. Creating an extra level of indirection as a way to use the paradigm in C++ since it facilitates calling functions which are determined at runtime from the same piece of code. They allow passing a function around as parameter or return value in another function. Using function pointers has exactly the same overhead as any other function call plus the additional pointer indirection and since the function to call is determined only at runtime the compiler will typically not inline the function call as it could do anywhere else. Because of this characteristics using function pointers may add up to be significantly slower than using regular function calls and be avoided as a way to gain performance. NOTE Function pointers are mostly used in C C++ also permits another constructs to enable that are called (class type functors and template type functors) that have some advantages over function pointers. To declare a pointer to a function naively the name of the pointer must be parenthesized otherwise a function returning a pointer will be declared. You also have to declare the function s return type and its parameters. These must be exact! Consider int ( ptof)(int arg) The function to be referenced must obviously have the same return type and the same parameter type as that of the pointer to function. The address of the function can be assigned just by using its name optionally prefixed with the address of operator . Calling the function can be done by using either ptof( ) or ( ptof)( ) . So int ( ptof)(int arg) int func(int arg){ //function body } ptof = func // get a pointer to func ptof = func // same effect as ptof = func ( ptof)(5) // calls func ptof(5) // same thing. A function returning a float can t be pointed to by a pointer ...