Non-Operator Overloads in Functors

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

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.

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.

Questions & Answers

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

Functors vs Lambda Expressions
When should I use a functor instead of a lambda expression in C++?
Templated operator() in Functors
Can the operator() in a functor be a template function?
Functors and Inheritance
Can a derived class override the operator() of a base functor class?
Functor vs Function Performance
Is there a performance difference between using functors and regular functions?
Capturing this in Functors
Can a functor capture the this pointer, and what are the implications?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant