PointerToFunction.cpp
TCP1, p. 215-216
download
// Defining and using a pointer to a function
#include <iostream>
using std::cout;
using std::endl;
void func();
int main()
{
void (*fp1)(); // Define a function pointer
fp1 = &func; // fp1 = func; // Initialize it
(*fp1)(); // Dereferencing calls the function, func()
fp1(); // alternate way to call the function
(*func)();
func();
void (*fp2)() = func; // Define and initialize
fp2 = fp1; // nothing changes, both pointers point to func()
// fp2 = &fp1; // compile error, both are pointers
(*fp2)(); // function call, func()
fp2 = &func;
fp2(); // same function call
return 0;
}
void func()
{
cout << "func() called..." << endl;
}
/*
g++ PointerToFunction.cpp -o PointerToFunction
./PointerToFunction
func() called...
func() called...
func() called...
func() called...
func() called...
func() called...
*/
Comments
Post a Comment