Pointer To Functions in C++

Pointer to functions in C++ is a feature that allows you to store and manipulate addresses of functions. This capability provides flexibility in program design, enabling dynamic function invocation, callback mechanisms, and implementation of advanced programming techniques such as function pointers in data structures and algorithms. Understanding pointer to functions is crucial for mastering C++ programming, especially in scenarios where runtime decisions dictate which function to call or when functions need to be passed as arguments to other functions.

Here’s an explanation of pointer to functions in C++:

Declaration: Similar to variables, you declare a pointer to a function by specifying its return type and parameters, followed by an asterisk (*) and the pointer name. For example

int (*ptrFunc)(int, int);

This declares a pointer to a function that takes two integers as parameters and returns an integer.

Assignment: After declaration, you can assign the address of a function to the pointer using the function name without parentheses. For example:

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

ptrFunc = sum;

Here, ptrFunc is assigned the address of the sum function.

Invocation: You can invoke the function using the pointer by dereferencing it and providing arguments as if you were calling the function directly. For example:

int result = (*ptrFunc)(3, 5);

This calls the sum function through the ptrFunc pointer with arguments 3 and 5 and stores the result in the variable result.

Dynamic Function Selection: Pointer to functions is particularly useful when you want to select and call different functions at runtime based on certain conditions or inputs. This allows for flexible program behavior and facilitates polymorphic behavior without the need for inheritance or virtual functions.

Callback Mechanisms: Function pointers are commonly used in callback mechanisms where functions are passed as arguments to other functions. This enables event-driven programming and asynchronous execution, common in graphical user interfaces (GUI) and event-driven systems.

Implementation of Data Structures and Algorithms: Function pointers are essential in implementing data structures such as function tables, callback lists, and event handlers. They enable generic programming techniques where algorithms can operate on different types of data using user-defined functions.

Now, let’s see an example C++ program demonstrating the usage of pointer to functions:

#include <iostream>

// Function to add two integers
int add(int a, int b) {
    return a + b;
}

// Function to subtract two integers
int subtract(int a, int b) {
    return a - b;
}

int main() {
    // Declare a pointer to a function taking two integers and returning an integer
    int (*ptrFunc)(int, int);

    // Assign the address of the add function to the pointer
    ptrFunc = add;

    // Call the function using the pointer
    int result = (*ptrFunc)(5, 3);
    std::cout << "Result of addition: " << result << std::endl;

    // Reassign the pointer to the subtract function
    ptrFunc = subtract;

    // Call the function using the pointer
    result = (*ptrFunc)(5, 3);
    std::cout << "Result of subtraction: " << result << std::endl;

    return 0;
}

Explanation:

  • We declare two functions add and subtract, each taking two integers and returning an integer.
  • In the main function, we declare a pointer to a function named ptrFunc, which takes two integers and returns an integer.
  • We assign the address of the add function to ptrFunc and call it to perform addition.
  • Then, we reassign ptrFunc to point to the subtract function and call it to perform subtraction.
  • Finally, we print the results of addition and subtraction.

Given below are few more example programs in C++ to explain Pointer to Functions

Pointer to Function with Different Signatures – Calculate Maximum

Introduction: This program demonstrates the usage of a pointer to function with different function signatures to calculate the maximum of two numbers.

#include <iostream>

int max(int a, int b) {
    return (a > b) ? a : b;
}

float max(float a, float b) {
    return (a > b) ? a : b;
}

int main() {
    // Pointer to function with different signatures
    int (*intPtr)(int, int) = max;
    float (*floatPtr)(float, float) = max;

    int intResult = intPtr(5, 3);
    float floatResult = floatPtr(5.5f, 3.3f);

    std::cout << "Maximum of 5 and 3 (int): " << intResult << std::endl;
    std::cout << "Maximum of 5.5 and 3.3 (float): " << floatResult << std::endl;

    return 0;
}

Explanation:

  • int max(int a, int b): Defines a function max that takes two integers as parameters and returns the maximum of the two.
  • float max(float a, float b): Defines another version of the max function that takes two floats as parameters and returns the maximum of the two.
  • int (*intPtr)(int, int) = max;: Declares a pointer to function intPtr that takes two integers as parameters and returns an integer. It is initialized with the address of the function max with integer parameters.
  • float (*floatPtr)(float, float) = max;: Declares a pointer to function floatPtr that takes two floats as parameters and returns a float. It is initialized with the address of the function max with float parameters.
  • Calls the function through the pointers intPtr and floatPtr to find the maximum of integers and floats, respectively.

This program demonstrates the usage of a pointer to function with different function signatures to calculate the maximum of two numbers.

Array of Function Pointers – Perform Arithmetic Operations

Introduction: This program demonstrates the usage of an array of function pointers to perform arithmetic operations.

#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) {
    if (b != 0) {
        return a / b;
    } else {
        std::cerr << "Error: Division by zero!" << std::endl;
        return 0;
    }
}

int main() {
    // Array of function pointers
    int (*operations[4])(int, int) = {add, subtract, multiply, divide};

    int a = 10, b = 5;

    for (int i = 0; i < 4; ++i) {
        std::cout << "Result of operation " << i + 1 << ": " << operations[i](a, b) << std::endl;
    }

    return 0;
}

Explanation:

  • int add(int a, int b), int subtract(int a, int b), int multiply(int a, int b), int divide(int a, int b): Define functions to perform addition, subtraction, multiplication, and division operations.
  • int (*operations[4])(int, int) = {add, subtract, multiply, divide};: Declares an array of function pointers operations with size 4, where each pointer points to a function that takes two integers as parameters and returns an integer. It is initialized with the addresses of the respective arithmetic functions.
  • Loop through the array of function pointers and call each function with a and b as arguments to perform the arithmetic operations.

This program demonstrates the usage of an array of function pointers to perform arithmetic operations.

Pointer to Function as a Callback Function

Introduction: This program demonstrates the usage of a pointer to function as a callback function to customize the behavior of a function.

#include <iostream>

void performOperation(int a, int b, int (*operation)(int, int)) {
    std::cout << "Result of operation: " << operation(a, b) << std::endl;
}

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

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

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

    std::cout << "Performing addition:" << std::endl;
    performOperation(a, b, add);

    std::cout << "Performing subtraction:" << std::endl;
    performOperation(a, b, subtract);

    return 0;
}

Explanation:

  • void performOperation(int a, int b, int (*operation)(int, int)): Defines a function performOperation that takes two integers a and b and a pointer to function operation as parameters. It calls the function operation with a and b.
  • int add(int a, int b), int subtract(int a, int b): Define functions to perform addition and subtraction operations.
  • Calls the performOperation function with add and subtract functions as arguments to perform addition and subtraction operations, respectively.

This program demonstrates the usage of a pointer to function as a callback function to customize the behavior of a function

Explanation:

  • void performOperation(int a, int b, int (*operation)(int, int)): Defines a function performOperation that takes two integers a and b and a pointer to function operation as parameters. It calls the function operation with a and b.
  • int add(int a, int b), int subtract(int a, int b): Define functions to perform addition and subtraction operations.
  • Calls the performOperation function with add and subtract functions as arguments to perform addition and subtraction operations, respectively.

This program demonstrates the usage of a pointer to function as a callback function to customize the behavior of a function

Pointer to Function with Lambda Expression

Introduction: This program demonstrates the usage of a pointer to function with a lambda expression to perform a custom operation.

#include <iostream>

int main() {
    // Pointer to function with lambda expression
    auto customOperation = [](int a, int b) { return a * a + b * b; };

    int result = customOperation(3, 4);

    std::cout << "Result of custom operation: " << result << std::endl;

    return 0;
}

Explanation:

  • auto customOperation = [](int a, int b) { return a * a + b * b; };: Defines a pointer to function customOperation using a lambda expression. The lambda expression takes two integers a and b as parameters and returns the result of the custom operation.
  • int result = customOperation(3, 4);: Calls the function customOperation with arguments 3 and 4 to perform the custom operation.

This program demonstrates the usage of a pointer to function with a lambda expression to perform a custom operation.

These examples provide a detailed understanding of pointers to functions in C++.