Functors in C++: What They Are and How They Simplify Code? A Complete Guide

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

What are functors in C++ and why are they needed?

\n\n

Imagine you are writing code in C++ and need to pass behavior (a function) to another function, for example, for sorting or filtering data. The classic solution is function pointers. But they have drawbacks: they cannot store state, they are difficult to inline, and they look a bit archaic. This is where functors in C++ (also known as function objects or C++ functional objects) come onto the scene.

\n\n

A functor is an ordinary class or struct in which the function call operator operator() is overloaded. Thanks to this, an instance of such a class can be used like an ordinary function. Sounds complicated? In reality, it is one of the most elegant tools in C++. On Stack Overflow, the question "What are C++ functors and their uses?" has garnered thousands of views — developers want to understand this topic to write more flexible and performant code. In this guide, we will break everything down: from basic syntax to real-world usage examples with STL.

\n\n

Basic syntax: how to create your first functor

\n\n

Creating a functor boils down to three steps:

\n
    \n
  • Declare a class or struct.
  • \n
  • Implement operator() inside it with the desired signature (parameters and return type).
  • \n
  • Create an object of this class and call it like a function.
  • \n
\n\n

Here is a simple C++ functor example that multiplies a number by two:

\n\n
#include <iostream>\n\nclass Multiplier {\npublic:\n    // Overload the () operator\n    int operator()(int x) const {\n        return x * 2;\n    }\n};\n\nint main() {\n    Multiplier mult;  // Create a function object\n    std::cout << mult(5) << std::endl; // Output: 10\n    std::cout << mult(10) << std::endl; // Output: 20\n    return 0;\n}
\n\n

Notice: mult(5) looks like a regular function call, but it is actually a call to mult.operator()(5). The compiler provides syntactic sugar, making the code clean and intuitive.

\n\n

Main advantage: functors can store state

\n\n

Unlike ordinary functions or lambda expressions (before C++11), C++ function objects can have their own member fields. This opens up enormous possibilities. For example, you can create a functor that not only performs an action but also remembers how many times it has been called:

\n\n
#include <iostream>\n\nclass Counter {\nprivate:\n    int count = 0;\npublic:\n    int operator()() {\n        return ++count;\n    }\n    int getCount() const { return count; }\n};\n\nint main() {\n    Counter counter;\n    std::cout << counter() << std::endl; // 1\n    std::cout << counter() << std::endl; // 2\n    std::cout << counter() << std::endl; // 3\n    // State is preserved between calls!\n    return 0;\n}
\n\n

This C++ functor example with state cannot be implemented using a simple function without global variables (which is bad). Functors solve this problem elegantly and safely.

\n\n

Functors and STL algorithms: a perfect match

\n\n

The most powerful application of functors is working with algorithms from the Standard Template Library (STL). Algorithms like std::sort, std::find_if, std::for_each expect a callable object as input. You can pass them a functor, and it will execute the required logic.

\n\n

Example: sorting with a functor

\n\n

Suppose you have a vector of numbers and you want to sort them in descending order. You can write your own comparison functor:

\n\n
#include <iostream>\n#include <vector>\n#include <algorithm>\n\nclass Descending {\npublic:\n    bool operator()(int a, int b) const {\n        return a > b; // Ret                

Blogs

Book Recommendations