Function Pointers in C++


Function pointers are pointers that point to a function instead of an object. In C++, function pointers can be used to call a function dynamically, pass a function as an argument to another function, and more.

 

Here's an example that demonstrates how function pointers can be used in C++:

#include <iostream>

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

int subtract(int a, int b) {
    return a - b;
}

int multiply(int a, int b) {
    return a * b;
}

int divide(int a, int b) {
    return a / b;
}

int main() {
    int a = 10, b = 5;

    // Declare a function pointer
    int (*p)(int, int);

    // Assign a pointer to the add function
    p = add;
    std::cout << p(a, b) << std::endl; // outputs "15"

    // Assign a pointer to the subtract function
    p = subtract;
    std::cout << p(a, b) << std::endl; // outputs "5"

    // Assign a pointer to the multiply function
    p = multiply;
    std::cout << p(a, b) << std::endl; // outputs "50"

    // Assign a pointer to the divide function
    p = divide;
    std::cout << p(a, b) << std::endl; // outputs "2"

    return 0;
}

In this example, we define four functions: add, subtract, multiply, and divide. We then declare a function pointer p and assign it to different functions at different times. Finally, we call the functions through the function pointer p.

 

Function pointers can be useful in various scenarios, such as implementing callbacks, implementing function objects, and more. By using function pointers, you can write more flexible and reusable code.

 

Summary

Function pointers in C++ are pointers that point to a function. They can be used to call a function dynamically, pass a function as an argument to another function, and more. Function pointers can be useful in various scenarios and help write more flexible and reusable code.

'C++' 카테고리의 다른 글

Compiling C++ Code on a Mac using the Terminal and GCC  (0) 2023.02.10
Key Features of C++14  (0) 2023.02.10
Lambda Functions in C++  (0) 2023.02.10
Overview of C++11 and C++14 Features  (0) 2023.02.10
Understanding Functions in C++  (0) 2023.01.12

+ Recent posts