C++ Pointers to Func

What is a Pointer to a Function in C++?

A pointer to a function is a variable that stores the address of a function. Yes, just like we store the address of data in a pointer, we can also store and call a function using its memory address! 🧠🔗

This is helpful when you want to choose which function to call at runtime or pass a function as a parameter. Think of it like calling a friend by their phone number. ☎️

🧠 Syntax of Function Pointer

return_type (*pointer_name)(parameter_list);

To assign a function to the pointer:

pointer_name = function_name;

To call the function using the pointer:

(*pointer_name)(arguments);

🔧 Example: Call Function Using Pointer

#include <iostream>
using namespace std;

void greet() {
    cout << "Hello from a pointer!" << endl;
}

int main() {
    void (*ptr)();  // Declare a pointer to function
    ptr = greet;    // Assign function address to pointer

    (*ptr)();       // Call the function using the pointer
    return 0;
}
  

Try It Now

🎯 Example: Pointer to Function with Parameters

#include <iostream>
using namespace std;

int add(int a, int b) {
    return a + b;
}

int main() {
    int (*ptr)(int, int);  // Pointer to function that takes two ints
    ptr = add;

    int result = (*ptr)(5, 3);
    cout << "Result: " << result << endl;
    return 0;
}
  

Try It Now

📦 Bonus: Pass Function Pointer to Another Function

You can pass a function pointer as an argument to another function!

#include <iostream>
using namespace std;

void greet() {
    cout << "Hi there!" << endl;
}

void runFunction(void (*funcPtr)()) {
    funcPtr();  // Call the function via pointer
}

int main() {
    runFunction(greet);
    return 0;
}
  

Try It Now

📌 Summary

  • A function pointer holds the address of a function
  • You can call a function through its pointer
  • You can pass a function pointer to another function

It’s like calling a function by phone 📞 — all you need is its address!