Referencing & Dereferencing of the Function Pointer in C++
When we talk about referencing & dereferencing in the context of function pointers in C++, it's about how we connect a function pointer to a function & how we use that pointer to call the function.
Referencing a function to a function pointer is straightforward. You simply assign the function to the function pointer without using parentheses. This is because using the function's name without parentheses gives the address of the function, which is what the pointer needs to refer to it.
Here's a simple example to illustrate referencing:
In this example, funcPtr is a function pointer that points to square. By writing funcPtr = square;, we're giving funcPtr the address of the square function, effectively referencing square through funcPtr.
Dereferencing a function pointer is how we call the function it points to. We use the function pointer as if it were the function itself, by adding parentheses and any required parameters. This might seem a bit magical, but all it's doing is telling the computer to jump to the function the pointer is referencing & run it.
Here's how we can extend our previous example to include dereferencing:
#include <iostream>
using namespace std;
int square(int x) {
return x * x;
}
int main() {
int (*funcPtr)(int) = square;
// Dereferencing: Using 'funcPtr' to call 'square'
int result = funcPtr(5);
cout << "The square of 5 is: " << result << endl;
return 0;
}
In this updated example, funcPtr(5) is dereferencing funcPtr. It's just like calling square(5) directly, but instead, we're going through the function pointer.
Function Pointer Used to Call a Function
Using a function pointer to call a function in C++ is like having a variable that you can use to execute different functions at different times. This can make your code more flexible & powerful because you can decide which function to run during the program's execution rather than having to decide when you write the code.
To use a function pointer to call a function, you first need to declare a function pointer that matches the signature of the function you want to call. Then, you assign the target function to your pointer & use the pointer to call the function.
Here's a basic example to demonstrate this:
C++
#include <iostream>
using namespace std;
// Function that adds two numbers
int add(int a, int b) {
return a + b;
}
// Function that multiplies two numbers
int multiply(int a, int b) {
return a * b;
}
int main() {
// Function pointer declaration
int (*operation)(int, int);
// Using the function pointer to call 'add'
operation = add;
cout << "Adding 10 and 5 gives: " << operation(10, 5) << endl;
// Reassigning the function pointer to call 'multiply'
operation = multiply;
cout << "Multiplying 10 and 5 gives: " << operation(10, 5) << endl;
return 0;
}
You can also try this code with Online C++ Compiler
Run Code
Output
Adding 10 and 5 gives: 15
Multiplying 10 and 5 gives: 50
In this example, operation is a function pointer that can point to any function taking two int parameters & returning an int. Initially, we point it to the add function & use it to add two numbers. Then, we change it to point to the multiply function & use it to multiply the same two numbers. This shows how function pointers can be used to dynamically decide which function to call.
This ability to switch which function is called by changing what the function pointer points to is particularly useful in situations where you need to apply different operations under different conditions but want to keep your code structure simple & clean.
Passing Function Pointer as a Parameter
In C++, you can pass a function pointer as a parameter to another function. This means you can tell one function to use another function to do something specific. It's like giving someone a tool and telling them, "Here, use this tool to get the job done." This can make your code more modular and flexible, allowing for more reusable and customizable components.
To pass a function pointer as a parameter, you first define a function that accepts a function pointer as its argument. Then, you call this function and pass the address of the function you want to use.
Here's how you can do it:
C++
#include <iostream>
using namespace std;
// A function to be passed as a pointer
void displayMessage() {
cout << "Hello from a function pointer!" << endl;
}
// A function that takes a function pointer as a parameter
void executeFunction(void (*func)()) {
// Call the function passed as a pointer
func();
}
int main() {
// Passing 'displayMessage' to 'executeFunction'
executeFunction(displayMessage);
return 0;
}
You can also try this code with Online C++ Compiler
Run Code
Output
Hello from a function pointer!
In this code, displayMessage is a simple function that prints a message. executeFunction is another function that takes a function pointer as its parameter. Inside executeFunction, we call the function pointed to by the passed function pointer (func()). In main, we call executeFunction and pass displayMessage to it. This results in displayMessage being called, and its message being printed.
This technique is useful when you want a function to perform a certain operation that can vary depending on the situation. Instead of writing several similar functions, you can write one function that takes a function pointer and pass different functions according to the needs of your program.
Frequently Asked Questions
Can function pointers point to any function?
Function pointers can point to any function that matches their signature, meaning the return type and the parameter types of the function must be the same as those specified in the function pointer's declaration.
Are function pointers only used for calling functions?
Besides calling functions, function pointers can be used for more advanced purposes like callbacks, which are functions passed as arguments to other functions to be invoked later. They're also useful in creating more flexible and modular code, allowing for functions to be selected and executed dynamically.
How do function pointers affect program performance?
Function pointers can slightly impact performance due to the additional level of indirection; however, this impact is usually minimal. The flexibility and modularity benefits they provide often outweigh the slight performance cost.
Conclusion
In this article, we've learned about the concept of function pointers in C++, starting from their syntax to more advanced uses like passing them as parameters to other functions. We've seen how they add flexibility and modularity to our code, allowing us to choose at runtime which functions to execute. This can make our programs more dynamic and adaptable to different needs.
You can refer to our guided paths on the Coding Ninjas. You can check our course to learn more about DSA, DBMS, Competitive Programming, Python, Java, JavaScript, etc. Also, check out some of the Guided Paths on topics such as Data Structure and Algorithms, Competitive Programming, Operating Systems, Computer Networks, DBMS, System Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.