Overloading the Function Call Operator

What is the purpose of overloading the function call operator ()?

Overloading the function call operator () allows objects of your custom type to be used as if they were functions. This is useful for creating function objects, also known as functors.

Here's an example of overloading the function call operator for a custom Multiplier class:

#include <iostream>

class Multiplier {
private:
  int factor;

public:
  Multiplier(int f) : factor(f) {}

  int operator()(int x) const {
    return x * factor;
  }
};

int main() {
  Multiplier doubler(2);
  Multiplier tripler(3);

  std::cout << doubler(5) << "\n";
  std::cout << tripler(4) << "\n";
}
10
12

In this example, the Multiplier class overloads the function call operator to take an integer parameter x and return the result of multiplying x by the factor stored in the Multiplier object.

This allows us to create Multiplier objects that behave like functions. We can invoke the function call operator on these objects just like we would call a regular function, passing arguments within parentheses.

Overloading the function call operator is particularly useful when working with algorithms and libraries that expect function objects, such as the STL algorithms that take predicate functions.

Operator Overloading

Discover operator overloading, allowing us to define custom behavior for operators when used with our custom types

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

Overloading the Subscript Operator
How can I overload the subscript operator [] for my custom type?
Overloading Comparison Operators
How can I overload comparison operators like == and < for my custom type?
Overloading Arithmetic Assignment Operators
How can I overload arithmetic assignment operators like += and *= for my custom type?
Overloading the Stream Insertion Operator
How can I overload the << operator to print objects of my custom type?
Overloading Operators for Type Conversions
Can I overload operators to perform type conversions for my custom type?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant