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
andsubtract
, each taking two integers and returning an integer. - In the
main
function, we declare a pointer to a function namedptrFunc
, which takes two integers and returns an integer. - We assign the address of the
add
function toptrFunc
and call it to perform addition. - Then, we reassign
ptrFunc
to point to thesubtract
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 functionmax
that takes two integers as parameters and returns the maximum of the two.float max(float a, float b)
: Defines another version of themax
function that takes two floats as parameters and returns the maximum of the two.int (*intPtr)(int, int) = max;
: Declares a pointer to functionintPtr
that takes two integers as parameters and returns an integer. It is initialized with the address of the functionmax
with integer parameters.float (*floatPtr)(float, float) = max;
: Declares a pointer to functionfloatPtr
that takes two floats as parameters and returns a float. It is initialized with the address of the functionmax
with float parameters.- Calls the function through the pointers
intPtr
andfloatPtr
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 pointersoperations
with size4
, 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
andb
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 functionperformOperation
that takes two integersa
andb
and a pointer to functionoperation
as parameters. It calls the functionoperation
witha
andb
.int add(int a, int b)
,int subtract(int a, int b)
: Define functions to perform addition and subtraction operations.- Calls the
performOperation
function withadd
andsubtract
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 functionperformOperation
that takes two integersa
andb
and a pointer to functionoperation
as parameters. It calls the functionoperation
witha
andb
.int add(int a, int b)
,int subtract(int a, int b)
: Define functions to perform addition and subtraction operations.- Calls the
performOperation
function withadd
andsubtract
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 functioncustomOperation
using a lambda expression. The lambda expression takes two integersa
andb
as parameters and returns the result of the custom operation.int result = customOperation(3, 4);
: Calls the functioncustomOperation
with arguments3
and4
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++.