Function Objects Functors
Write classes with operator() to create stateful callable objects.
What is a Functor?
A functor (function object) is a class that overloads operator(). Instances can be called like functions.
struct Square {
int operator()(int x) const { return x * x; }
};
Square sq;
std::cout << sq(5); // 25Why Not Just a Function?
Functors carry state. A plain function does not. State enables configuration, counting, and stateful callbacks.
struct Counter {
int count = 0;
int operator()(int x) { ++count; return x; }
};
Counter c;
c(10); c(20); c(30);
std::cout << c.count; // 3