codingstuff.io
ExploreTutorialsProblemsCS Subjects
Get Started
ExploreTutorialsProblemsCS Subjects
Get Started
codingstuff.io

Master the art of building software through interactive tutorials, real-world problems, and guided projects.

Pune, Maharashtra, India

codingstuffmail@gmail.com

Product

  • Explore
  • Tutorials
  • Problems
  • CS Subjects

Company

  • About
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Sitemap

© 2026 codingstuff.io. All rights reserved.

Built with ❤️ for developers everywhere

/
/
All Tutorials
⚡

C++ Programming

75 / 87 topics
62Introduction to STL & Containers63std::array64Vectors65List & Forward List66Deque67Stack68Queue & Priority Queue69Map & Multimap70Set & Multiset71Unordered Map & Unordered Multimap72Unordered Set & Unordered Multiset73Iterators74Algorithms75Functors
Tutorials/C++ Programming/Functors
⚡C++ Programming

Functors

Updated 2026-05-12
30 min read

Functors

In the world of C++, functors are a powerful tool that allow you to treat functions as objects. This capability is particularly useful when working with algorithms from the Standard Template Library (STL), which often require function-like entities as arguments. In this tutorial, we'll dive deep into functors, exploring how they work, their differences from lambdas, and how to use them effectively.

Introduction

Functors are objects that can be treated like functions because they define the operator() member function. This means you can invoke a functor using the syntax similar to a regular function call. Functors offer several advantages over traditional functions, such as the ability to maintain state and encapsulate behavior within an object.

Understanding functors is crucial when working with STL algorithms, as many of them accept function objects (functors) as parameters. This tutorial will guide you through the basics of functors, their implementation, predefined functors in the STL, and how they compare to lambdas.

Core Content

What Are Functors?

A functor is a class that implements the operator() member function. This allows instances of the class to be called like functions. Here's a simple example to illustrate:

simple_functor.cpp
1#include <iostream>
2
3class Multiply {
4public:
5 int operator()(int x, int y) {
6 return x * y;
7 }
8};
9
10int main() {
11 Multiply multiplyObj;
12 std::cout << "Result: " << multiplyObj(3, 4) << std::endl; // Outputs: Result: 12
13 return 0;
14}
Output
Result: 12

In this example, the Multiply class defines an operator() that takes two integers and returns their product. We create an instance of Multiply, multiplyObj, and call it like a function with (3, 4).

Operator() Overloading

The key to making a class a functor is overloading the operator(). This operator can take any number of parameters and return any type, just like a regular function. Here's another example that demonstrates this:

overloaded_operator.cpp
1#include <iostream>
2
3class Increment {
4public:
5 int operator()(int x) const {
6 return x + 1;
7 }
8};
9
10int main() {
11 Increment inc;
12 std::cout << "Incremented: " << inc(5) << std::endl; // Outputs: Incremented: 6
13 return 0;
14}
Output
Incremented: 6

In this example, the Increment class overloads the operator() to increment an integer by 1. The const keyword indicates that this function does not modify the state of the functor.

Predefined Functors in STL

The Standard Template Library (STL) provides several predefined functors that you can use out of the box. These include:

  • plus: Adds two values.
  • minus: Subtracts the second value from the first.
  • multiplies: Multiplies two values.
  • divides: Divides the first value by the second.
  • modulus: Computes the modulus (remainder) of division.
  • negate: Negates a value.

Here's how you can use these predefined functors:

predefined_functors.cpp
1#include <iostream>
2#include <functional> // Include for predefined functors
3
4int main() {
5 std::plus<int> add;
6 std::minus<int> subtract;
7 std::multiplies<int> multiply;
8 std::divides<int> divide;
9
10 std::cout << "Add: " << add(5, 3) << std::endl; // Outputs: Add: 8
11 std::cout << "Subtract: " << subtract(5, 3) << std::endl; // Outputs: Subtract: 2
12 std::cout << "Multiply: " << multiply(5, 3) << std::endl; // Outputs: Multiply: 15
13 std::cout << "Divide: " << divide(5, 3) << std::endl; // Outputs: Divide: 1
14
15 return 0;
16}
Output
Add: 8
Subtract: 2
Multiply: 15
Divide: 1

In this example, we use the std::plus, std::minus, std::multiplies, and std::divides functors to perform basic arithmetic operations.

Functors vs. Lambdas

Functors and lambdas both allow you to define callable objects in C++. However, there are several differences between them:

  • Syntax: Lambdas provide a more concise syntax for defining anonymous functions on the fly.
  • State: Functors can maintain state because they are regular classes with member variables. Lambdas can capture variables from their surrounding scope, but this is limited to copy or reference capturing.
  • Performance: In some cases, functors can be more efficient than lambdas due to better optimization opportunities.

Here's a comparison using both a functor and a lambda:

functor_vs_lambda.cpp
1#include <iostream>
2#include <functional>
3
4class Multiply {
5public:
6 int operator()(int x, int y) {
7 return x * y;
8 }
9};
10
11int main() {
12 // Using a functor
13 Multiply multiplyObj;
14 std::cout << "Functor Result: " << multiplyObj(3, 4) << std::endl; // Outputs: Functor Result: 12
15
16 // Using a lambda
17 auto multiplyLambda = [](int x, int y) { return x * y; };
18 std::cout << "Lambda Result: " << multiplyLambda(3, 4) << std::endl; // Outputs: Lambda Result: 12
19
20 return 0;
21}
Output
Functor Result: 12
Lambda Result: 12

In this example, both the functor and the lambda achieve the same result. However, functors are more flexible when it comes to maintaining state or encapsulating complex behavior.

Practical Example

Let's create a practical example that demonstrates the use of functors with STL algorithms. We'll sort a vector of integers in descending order using a custom functor:

practical_functor.cpp
1#include <iostream>
2#include <vector>
3#include <algorithm>
4
5class Greater {
6public:
7 bool operator()(int x, int y) const {
8 return x > y;
9 }
10};
11
12int main() {
13 std::vector<int> numbers = {5, 2, 9, 1, 5, 6};
14
15 // Sort using the custom functor
16 std::sort(numbers.begin(), numbers.end(), Greater());
17
18 // Print sorted vector
19 for (int num : numbers) {
20 std::cout << num << " ";
21 }
22 std::cout << std::endl; // Outputs: 9 6 5 5 2 1
23
24 return 0;
25}
Output
9 6 5 5 2 1

In this example, we define a Greater functor that compares two integers and returns true if the first is greater than the second. We then use std::sort with an instance of Greater to sort a vector in descending order.

Summary

ConceptDescription
FunctorA class that implements the operator() member function, allowing instances to be called like functions.
Operator()The overloaded operator that makes a class behave like a function.
Predefined FunctorsSTL functors like plus, minus, etc., for common operations.
Functors vs. LambdasFunctors are more flexible in maintaining state, while lambdas offer concise syntax and capture capabilities.

What's Next?

Now that you have a solid understanding of functors, the next step is to explore the &lt;iostream&gt; library, which provides essential input and output functionalities in C++. This will help you build more interactive programs.


PreviousAlgorithmsNext <iostream> Reference

Recommended Gear

Algorithms<iostream> Reference