The Wayback Machine - https://web.archive.org/web/20240723214732/https://www.geeksforgeeks.org/passing-a-function-as-a-parameter-in-cpp/
Open In App

Passing a Function as a Parameter in C++

Last Updated : 10 Oct, 2022
Improve
Suggest changes
Post a comment
Like Article
Like
Save
Share
Report

A function is a set of statements that take inputs, perform some specific computation, and produce output. The idea to use functions is to perform some commonly or repeatedly done tasks together and make a function so that instead of writing the same code again and again for different inputs.

The general form of a function is in the below format:

return_type function_name([ arg1_type arg1_name, ... ]) 
{
     // Perform Operations
}

Passing a function as an argument is a useful concept in C++. This concept has already been used while passing a custom comparator function as an argument in std::sort() to sort a sequence of objects as per the need. In this article, we will discuss different ways to design functions that accept another function as an argument.

A function can be passed as a parameter with 3 approaches i.e.

  1. Passing as Pointer 
  2. Using std::function<>
  3. Using Lambdas

1. Passing Pointer to a Function

A function can also be passed to another function by passing its address to that function; In simple terms, it could be achieved via pointers.

Example:

C++




// C++ program to pass function as a
// pointer to any function
#include <iostream>
using namespace std;
 
// Function that add two numbers
int add(int x, int y) { return x + y; }
 
// Function that multiplies two
// numbers
int multiply(int x, int y) { return x * y; }
 
// Function that takes a pointer
// to a function
int invoke(int x, int y, int (*func)(int, int))
{
    return func(x, y);
}
 
// Driver Code
int main()
{
    // Pass pointers to add & multiply
    // function as required
    cout << "Addition of 20 and 10 is ";
    cout << invoke(20, 10, &add;) << '\n';
 
    cout << "Multiplication of 20"
         << " and 10 is ";
    cout << invoke(20, 10, &multiply;) << '\n';
 
    return 0;
}


Output:

Addition of 20 and 10 is 30
Multiplication of 20 and 10 is 200

2. Using std::function<>

In C++ 11, there is a std::function<> template class that allows to pass functions as objects. An object of std::function<> can be created as follows. 

std::function<return_type(arg1_type, arg2-type...)> obj_name

   //  This object can be use to call the function as below
   return_type catch_variable = obj_name(arg1, arg2);

Example:

C++




// C++ program to demonstrate the passing
// of functions as an object parameter
#include <functional>
#include <iostream>
using namespace std;
 
// Define add and multiply to
// return respective values
int add(int x, int y) { return x + y; }
int multiply(int x, int y) { return x * y; }
 
// Function that accepts an object of
// type std::function<> as a parameter
// as well
int invoke(int x, int y, function<int(int, int)> func)
{
    return func(x, y);
}
 
// Driver code
int main()
{
    // Pass the required function as
    // parameter using its name
    cout << "Addition of 20 and 10 is ";
    cout << invoke(20, 10, &add;) << '\n';
 
    cout << "Multiplication of 20"
         << " and 10 is ";
    cout << invoke(20, 10, &multiply;) << '\n';
 
    return 0;
}


Output:

Addition of 20 and 10 is 30
Multiplication of 20 and 10 is 200

3. Using Lambdas

Lambdas in C++ provide a way to define inline, one-time, anonymous function objects. These lambdas can be defined in a place where it is required to pass a function as an argument. 

Example:

C++




// C++ program to pass the function as
// parameter as a lambda expression
#include <functional>
#include <iostream>
using namespace std;
 
// Function that takes a pointer
// to a function
int invoke(int x, int y,
           function<int(int, int)> func)
{
    return func(x, y);
}
 
// Driver Code
int main()
{
 
    // Define lambdas for addition and
    // multiplication operation where
    // we want to pass another function
    // as a parameter
 
    // Perform Addition
    cout << "Addition of 20 and 10 is ";
    int k = invoke(20, 10,
                   [](int x,
                      int y) -> int {
                       return x + y;
                   });
 
    cout << k << '\n';
 
    // Perform Multiplication
    cout << "Multiplication of 20"
         << " and 10 is ";
    int l = invoke(20, 10,
                   [](int x,
                      int y) -> int {
                       return x * y;
                   });
 
    cout << l << '\n';
 
    return 0;
}


Output:

Addition of 20 and 10 is 30
Multiplication of 20 and 10 is 200


Previous Article
Next Article

Similar Reads

Passing By Pointer vs Passing By Reference in C++
In C++, we can pass parameters to a function either by pointers or by reference. In both cases, we get the same result. So, what is the difference between Passing by Pointer and Passing by Reference in C++? Let's first understand what Passing by Pointer and Passing by Reference in C++ mean: Passing by Pointer Here, the memory location (address) of
5 min read
Passing array of objects as parameter in C++
Array of Objects:It is an array whose elements are of the class type. It can be declared as an array of any datatype. Syntax: classname array_name [size]; Below is the C++ program to illustrate the array of objects by calculating the highest marks among 3 students: C/C++ Code // C++ program to illustrate the // passing the array of objects // to fu
3 min read
Parameter Passing Techniques in C++
In C++, data must be sent to functions when they are called in order to perform operations. This data is called parameters or arguments and there are various parameter passing methods available in C++, each with merits and demerits of its own. In this article, we will discuss various parameter-passing techniques in C++. Basic TerminologiesFunction
4 min read
Parameter Passing Techniques in C
In C, there are different ways in which parameter data can be passed into and out of methods and functions. Let us assume that a function B() is called from another function A(). In this case, A is called the "caller function" and B is called the "called function or callee function". Also, the arguments which A sends to B are called actual argument
5 min read
Const Reference vs Normal Parameter Passing in C++
In C++, when we call a function we can also pass the parameters to the function in many ways like pass by value, pass by reference, pass by pointer, and by const reference. Each parameter-passing technique has its own advantages and disadvantages. In this article, we will learn the difference between normal parameter passing and passing by const re
4 min read
Passing Vector to a Function in C++
When we pass an array to a function, a pointer is actually passed. However, to pass a vector there are two ways to do so: Pass By valuePass By Reference When a vector is passed to a function, a copy of the vector is created. This new copy of the vector is then used in the function and thus, any changes made to the vector in the function do not affe
3 min read
Passing a vector to constructor in C++
When class member is a vector object (not a reference).We can simply assign in constructor. C/C++ Code // Passing vector object to a constructor. #include &amp;lt;iostream&amp;gt; #include &amp;lt;vector&amp;gt; using namespace std; class MyClass { vector&amp;lt;int&amp;gt; vec; public: MyClass(vector&amp;lt;int&amp;gt; v) { vec = v; } void print()
2 min read
Passing Reference to a Pointer in C++
Prerequisite: Pointers vs References in C++. For clear understanding, let's compare the usage of a "pointer to pointer" VS "Reference to pointer" in some cases. Note: It is allowed to use "pointer to pointer" in both C and C++, but we can use "Reference to pointer" only in C++. Passing pointer to a function If a pointer is passed to a function as a
4 min read
How to delete an element from the Set by passing its value in C++
Given a Set, the task is to remove the last element from this Set in C++.Examples: Input: set = [10 20 30 70 80 90 100 40 50 60], valueOfElementToBeDeleted = 100 Output: 10 20 30 40 50 60 70 80 90 Input: set = [1 2 3 4 5], valueOfElementToBeDeleted = 3 Output: 1 2 4 5 Sets are a type of associative container in which each element has to be unique b
6 min read
Passing and Returning Objects in C++
In C++ we can pass class's objects as arguments and also return them from a function the same way we pass and return other variables. No special keyword or header file is required to do so. Passing an Object as argument To pass an object as an argument we write the object name as the argument while calling the function the same way we do it for oth
4 min read
Practice Tags :
three90RightbarBannerImg