Functional Objects and Functors in C++


In C++, functional objects (also known as functors) are objects that can be used as though they were a function. They are implemented by overloading the operator() in a class or struct, enabling objects of that class to be called like a function.

What Are Functional Objects (Functors)?

A functional object is an instance of a class or struct that defines the operator(). It can store state and behavior, making it more versatile than plain functions.

Example:

    #include <iostream>
    using namespace std;

    class Adder {
        int value;
    public:
        Adder(int v) : value(v) {}
        int operator()(int x) const {
            return x + value;
        }
    };

    int main() {
        Adder addFive(5); // Create a functor
        cout << "5 + 10 = " << addFive(10) << endl; // Use the functor
        return 0;
    }
        

Advantages of Functors

  • They can store data as member variables.
  • They allow function-like behavior with added flexibility.
  • They are compatible with STL algorithms that accept callable objects.

Examples of Functors

1. Custom Functor

Here is an example of a functor that multiplies a number by a given factor:

    #include <iostream>
    using namespace std;

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

    int main() {
        Multiplier multiplyBy3(3); // Functor to multiply by 3
        cout << "3 * 7 = " << multiplyBy3(7) << endl;
        return 0;
    }
        

2. Using Functors with STL Algorithms

Functors can be passed to STL algorithms like std::for_each:

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

    class Print {
    public:
        void operator()(int x) const {
            cout << x << " ";
        }
    };

    int main() {
        vector numbers = {1, 2, 3, 4, 5};
        for_each(numbers.begin(), numbers.end(), Print()); // Use functor
        return 0;
    }
        

3. Functor with State

A functor can maintain internal state to track data:

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

    class Counter {
        int count;
    public:
        Counter() : count(0) {}
        void operator()(int x) {
            if (x % 2 == 0) {
                count++;
            }
        }
        int getCount() const {
            return count;
        }
    };

    int main() {
        vector numbers = {1, 2, 3, 4, 5, 6};
        Counter counter = for_each(numbers.begin(), numbers.end(), Counter());
        cout << "Number of even numbers: " << counter.getCount() << endl;
        return 0;
    }
        

4. Predefined Functors in STL

C++ provides predefined functors in the <functional> header, such as plus, minus, multiplies, and greater:

    #include <iostream>
    #include <functional>
    using namespace std;

    int main() {
        plus add;
        cout << "10 + 20 = " << add(10, 20) << endl;

        greater compare;
        cout << "Is 10 greater than 5? " << (compare(10, 5) ? "Yes" : "No") << endl;

        return 0;
    }
        

Conclusion

Functors in C++ provide a powerful way to define callable objects with state and behavior. They are widely used with STL algorithms to enhance flexibility and make the code more modular and reusable.





Advertisement