Function Objects (Functors)

Non-Operator Overloads in Functors

Can a functor class contain non-operator overloads, and how do I call them?

Abstract art representing computer programming

Yes, a functor class can contain non-operator member functions, just like any other class. These functions can be called using the dot notation on an instance of the functor.

Here's an example of a functor with a regular member function:

#include <iostream>

class Functor {
public:
  void operator()() const {
    std::cout << "Calling operator()\n";
  }

  void SayHello() const {
    std::cout << "Hello from Functor!\n";
  }
};

int main() {
  Functor f;
  f(); // Call operator()
  f.SayHello(); // Call SayHello() 
}
Calling operator()
Hello from Functor!

You can also call non-operator member functions on a temporary functor instance:

#include <iostream>

class Functor {
 public:
  void SayHello() const {
    std::cout << "Hello from Functor!\n";
  }
};

int main() {
  Functor().SayHello();  
}
Hello from Functor!

This creates a temporary Functor object, calls SayHello() on it, and then immediately destroys the temporary object.

Non-operator member functions in functors can be useful for providing additional functionality related to the callable, such as setting up state or returning information about the functor's current state.

This Question is from the Lesson:

Function Objects (Functors)

This lesson introduces function objects, or functors. This concept allows us to create objects that can be used as functions, including state management and parameter handling.

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

This Question is from the Lesson:

Function Objects (Functors)

This lesson introduces function objects, or functors. This concept allows us to create objects that can be used as functions, including state management and parameter handling.

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