Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Last Updated: Mar 27, 2024
Difficulty: Easy

Function Pointer in C++

Leveraging ChatGPT - GenAI as a Microsoft Data Expert
Speaker
Prerita Agarwal
Data Specialist @
23 Jul, 2024 @ 01:30 PM

Introduction

C++ is a powerful programming language that lets us talk to our computers & tell them what to do. One of the cool features it offers is something called a function pointer. Now, you might wonder, what's that? Imagine you have a remote control (the function pointer) that can be programmed to control different devices (functions). This means you can decide which device you want to control without needing a separate remote for each one. 

Function Pointer in C++

In this article, we're going to explore how these "remotes" work in C++, how to use them to call functions, & even pass them around like variables. It's like having a superpower in the coding world, & we'll show you how to use it.

Syntax of Function Pointers in C++

Getting into the syntax of function pointers might sound a bit scary at first, but it's really just a way of telling your program how to find and use functions. Think of it as giving your computer a map to find the function you want it to run. In C++, the syntax for a function pointer goes a bit like this:

return_type (*pointer_name)(parameter_types);

 

  • return_type: This is what the function gives back after it finishes. For example, if it's supposed to calculate something & give you a number, this could be int for an integer.
     
  • pointer_name: This is just what you decide to call your function pointer. It's like naming a pet; the name itself doesn't change anything about how it works.
     
  • parameter_types: Here, you list what kind of stuff your function needs to know to do its job.For example, if it's adding two numbers, you'd need two integers here.

 

For example:

  • C++

C++

#include <iostream>
using namespace std;

// A function we want to point to
void greet() {
cout << "Hello, World!" << endl;
}

int main() {
// Creating a function pointer named 'funcPtr' pointing to 'greet'
void (*funcPtr)() = greet;

// Using the function pointer to call 'greet'
funcPtr();

return 0;
}


Output

Hello, World!


In this example, funcPtr is a pointer to the function greet, which doesn't take any parameters & doesn't return anything (void). By setting funcPtr to greet, we can call greet() just by using funcPtr(). It's like having a shortcut to call the function.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

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++

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;
}

 

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++

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;
}

 

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 DSADBMSCompetitive ProgrammingPythonJavaJavaScript, etc. Also, check out some of the Guided Paths on topics such as Data Structure and AlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.

Topics covered
1.
Introduction
2.
Syntax of Function Pointers in C++
2.1.
C++
3.
Referencing & Dereferencing of the Function Pointer in C++
4.
Function Pointer Used to Call a Function
4.1.
C++
5.
Passing Function Pointer as a Parameter
5.1.
C++
6.
Frequently Asked Questions
6.1.
Can function pointers point to any function?
6.2.
Are function pointers only used for calling functions?
6.3.
How do function pointers affect program performance?
7.
Conclusion