Operator Overloading

Overloading the Function Call Operator

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

Abstract art representing computer programming

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.

This Question is from the Lesson:

Operator Overloading

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

Answers to questions are automatically generated and may not have been reviewed.

This Question is from the Lesson:

Operator Overloading

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

A computer programmer
Part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

  • 125 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved