Skip to content

C++ Functor Tutorial

A functor (function object) in C++ is any object that can be called as if it were a function. This is achieved by overloading the operator() in a class or struct.

Functors are useful for customizing behavior, especially in algorithms and STL containers.


1. Basic Functor Example

#include <iostream>
using namespace std;

struct Add {
    int operator()(int a, int b) const {
        return a + b;
    }
};

int main() {
    Add add;
    cout << add(3, 4) << endl; // Output: 7
    return 0;
}

2. Why Use Functors?

  • Stateful: Functors can hold state/data.
  • Custom Behavior: Pass custom logic to STL algorithms (e.g., sort, for_each).
  • Performance: Can be inlined by the compiler.

3. Functor with State

#include <iostream>
using namespace std;

struct Multiplier {
    int factor;
    Multiplier(int f) : factor(f) {}
    int operator()(int x) const {
        return x * factor;
    }
};

int main() {
    Multiplier times3(3);
    cout << times3(5) << endl; // Output: 15
    return 0;
}

4. Functors in STL Algorithms

#include <algorithm>
#include <vector>
#include <iostream>
using namespace std;

struct Print {
    void operator()(int x) const {
        cout << x << " ";
    }
};

int main() {
    vector<int> v = {1, 2, 3, 4};
    for_each(v.begin(), v.end(), Print());
    // Output: 1 2 3 4
    return 0;
}

5. Comparison Functor Example

#include <algorithm>
#include <vector>
#include <iostream>
using namespace std;

struct Descending {
    bool operator()(int a, int b) const {
        return a > b;
    }
};

int main() {
    vector<int> v = {4, 2, 5, 1};
    sort(v.begin(), v.end(), Descending());
    for (int x : v) cout << x << " "; // Output: 5 4 2 1
    return 0;
}

6. Lambda vs Functor

C++11 introduced lambdas, which are often more concise than functors for simple cases. However, functors are still useful for more complex or reusable logic.

sort(v.begin(), v.end(), [](int a, int b) { return a > b; });

Summary

  • A functor is any object with operator() defined.
  • Functors can store state and be reused.
  • Widely used in STL and custom algorithms.
  • Lambdas are a modern alternative