The Wayback Machine - https://web.archive.org/web/20241001194021/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
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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
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
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
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 &lt;iostream&gt; #include &lt;vector&gt; using namespace std; class MyClass { vector&lt;int&gt; vec; public: MyClass(vector&lt;int&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
Equation of straight line passing through a given point which bisects it into two equal line segments
Given a straight line which passes through a given point (x0, y0) such that this point bisects the line segment in two equal line segments. The task is to find the equation of this straight line.Examples: Input: x0 = 4, y0 = 3 Output: 3x + 4y = 24Input: x0 = 7, y0 = 12 Output: 12x + 7y = 168 Approach: Let PQ be the line and AB be the line segment b
4 min read
Passing Map as Reference in C++ STL
Prerequisite: Maps in C++ STL Pass by reference Elements in the map are in form of pairs where the first is key and another value, denoting key-value pairs. Also, all the key values are unique means no two elements can have the same key value. Passing maps by value is a costly task, costly in terms of computation and memory resources. When we pass
3 min read
Passing Pointers to Functions In C++
Prerequisites: Pointers in C++Functions in C++ Passing Pointers to functions means declaring the function parameter as a pointer, at the function calling passing the address of the variable and that address will be stored by a parameter that is declared as a pointer. To change the value of any variable in the function we have to pass the address of
4 min read
Difference between Argument and Parameter in C/C++ with Examples
Argument An argument is referred to the values that are passed within a function when the function is called. These values are generally the source of the function that require the arguments during the process of execution. These values are assigned to the variables in the definition of the function that is called. The type of the values passed in
4 min read
How to print size of array parameter in C++?
How to compute the size of an array CPP? C/C++ Code // A C++ program to show that it is wrong to  // compute size of an array parameter in a function #include <iostream> using namespace std; void findSize(int arr[]) { cout << sizeof(arr) << endl; } int main() { int a[10]; cout << sizeof(a) << " "; findSize(a)
3 min read
error: call of overloaded ‘function(x)’ is ambiguous | Ambiguity in Function overloading in C++
Pre-requisite: Function Overloading in C++ Function overloading is a feature of object-oriented programming where two or more functions can have the same name but different parameters. When a function name is overloaded with different jobs it is called Function Overloading. Two or more functions are said to be overloaded if they differ in any of th
9 min read
How to call some function before main() function in C++?
Since it is known that main() method is the entry point of the program. Hence it is the first method that will get executed by the compiler. But this article explains how to call some function before the main() method gets executed in C++. How to call some function before main() function? To call some function before main() method in C++, Create a
3 min read
Difference between user defined function and library function in C/C++
Library Functions These functions are the built-in functions i.e., they are predefined in the library of the C. These are used to perform the most common operations like calculations, updation, etc. Some of the library functions are printf, scanf, sqrt, etc. To use these functions in the program the user has to use a header file associated with the
3 min read
Difference between virtual function and inline function in C++
Virtual function: Virtual function is a member function which is declared within a base class and is redefined by a derived class. Inline function: Inline function is a normal function which is defined by the keyword inline, it is a short function which is expanded by the compiler and its arguments are evaluated only once. The syntax of defining th
2 min read
Difference Between Friend Function and Virtual Function in C++
A friend class can access private and protected members of other classes in which it is declared as friend. It is sometimes useful to allow a particular class to access private members of other classes. Just likely, a friend function is a function that is declared outside the scope of a class. This function can be invoked like a normal function and
3 min read
What happens when a virtual function is called inside a non-virtual function in C++
Predict the output of the following simple C++ program without any virtual function. C/C++ Code #include &lt;iostream&gt; using namespace std; class Base { public: void print() { cout &lt;&lt; &quot;Base class print function \n&quot;; } void invoke() { cout &lt;&lt; &quot;Base class invoke function \n&quot;;
2 min read
Function Overloading vs Function Overriding in C++
Function Overloading (achieved at compile time) Function Overloading provides multiple definitions of the function by changing signature i.e. changing number of parameters, change datatype of parameters, return type doesn’t play any role. It can be done in base as well as derived class.Example: void area(int a); void area(int a, int b); C/C++ Code
3 min read
Function Pointer to Member Function in C++
In C++, function pointers enable users to treat functions as objects. They provide a way to pass functions as arguments to other functions. A function pointer to a member function is a pointer that points to a non-static member function of a class. In this article, we will learn how to use a function pointer to a member function in C++. Function Po
3 min read
Difference between Virtual function and Pure virtual function in C++
Virtual Function in C++ A virtual function is a member function which is declared within a base class and is re-defined(Overridden) by a derived class. When you refer to a derived class object using a pointer or a reference to the base class, you can call a virtual function for that object and execute the derived class’s version of the function. Pu
2 min read
Function Overloading vs Function Templates in C++
In C++, both function overloading and function templates allow us to create functions that can operate on different types of data. While they might seem similar, they are used for different purposes. In this article, we will learn the differences between function overloading and function templates, and understand when to use each. Table of Content
4 min read
How to call function within function in C or C++
When we begin programming in C/C++, we generally write one main() function and write all our logic inside this. This approach is fine for very small programs, but as the program size grows, this become unmanageable. So we use functions. We write code in the form of functions. The main function always acts as a driver function and calls other functi
4 min read
Can We Call an Undeclared Function in C++?
Calling an undeclared function is a poor style in C (See this) and illegal in C++and so is passing arguments to a function using a declaration that doesn't list argument types.If we call an undeclared function in C and compile it, it works without any error. But, if we call an undeclared function in C++, it doesn't compile and generates errors. In
2 min read
Can We Use Function on Left Side of an Expression in C and C++?
In C, it is not possible to have function names on the left side of an expression, but it's possible in C++. How can we use the function on the left side of an expression in C++? In C++, only the functions which return some reference variables can be used on the left side of an expression. The reference works in a similar way to pointers, so whenev
1 min read
Default Arguments and Virtual Function in C++
Default Arguments are the values provided during function declaration, such that values can be automatically assigned if no argument is passed to them. In case any value is passed the default value is overridden and it becomes a parameterized argument. Virtual function is a member function that is declared within a base class and is redefined(Overr
3 min read
How to Return a Local Array From a C++ Function?
Here, we will build a C++ program to return a local array from a function. And will come across the right way of returning an array from a function using 3 approaches i.e. Using Dynamically Allocated ArrayUsing Static Array Using Struct C/C++ Code // C++ Program to Return a Local // Array from a function While // violating some rules #include <i
3 min read
Practice Tags :