Function Pointer

A function pointer is a variable that can store the address of a function. It allows you to call a function indirectly by using the pointer. This feature is particularly useful when you want to pass a function as an argument to another function or store different functions in a data structure, such as an array.

Here’s an example that demonstrates the usage of function pointers in C++:

#include <iostream>

// Function with an int parameter
void printNumber(int number) {
    std::cout << "Number: " << number << std::endl;
}

// Function with a string parameter
void printMessage(const std::string& message) {
    std::cout << "Message: " << message << std::endl;
}

int main() {
    // Declare function pointers
    void (*funcPtr1)(int);
    void (*funcPtr2)(const std::string&);

    // Assign addresses of functions to function pointers
    funcPtr1 = printNumber;
    funcPtr2 = printMessage;

    // Call functions indirectly using function pointers
    funcPtr1(42);
    funcPtr2("Hello, World!");

    return 0;
}

In this example, we have two functions: printNumber and printMessage. The first function takes an int parameter and prints the number, while the second function takes a std::string parameter and prints the message.

Inside the main function, we declare two function pointers: funcPtr1 and funcPtr2. We then assign the addresses of the respective functions to these pointers. Finally, we call the functions indirectly using the function pointers, passing the required arguments.

The output of the program will be:

Number: 42
Message: Hello, World!

This demonstrates how function pointers can be used to call different functions based on the address stored in the pointer.

Leave a Reply

Your email address will not be published. Required fields are marked *