Using Function Pointers
When we use the name of a function as a value, the function is automatically converted to a pointer. For example, we can assign the address of lengthCompare
to pf
as follows:
pf = lengthCompare; // pf now points to the function named lengthComparepf = &lengthCompare; // equivalent assignment: address-of operator is optional
Moreover, we can use a pointer to a function to call the function to which the pointer points. We can do so directly—there is no need to dereference the pointer:
bool b1 = pf("hello", "goodbye"); // calls lengthComparebool b2 = (*pf)("hello", "goodbye"); // equivalent callbool b3 = lengthCompare("hello", "goodbye"); // equivalent call
There is no conversion between pointers to one function type ...
Get C++ Primer, Fifth Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.