Functors and Inheritance

Can a derived class override the operator() of a base functor class?

Yes, a derived class can override the operator() of a base functor class. This allows for polymorphic behavior when using functors in an inheritance hierarchy.

Here's an example:

#include <iostream>

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

class DerivedFunc : public BaseFunc {
 public:
  void operator()() const override {  
    std::cout << "DerivedFunc operator()\n";
  }
};

void CallFunc(const BaseFunc& func) {
  func();  
}

int main() {
  BaseFunc base;
  DerivedFunc derived;

  // Calls BaseFunc::operator()
  CallFunc(base);

  // Calls DerivedFunc::operator()
  CallFunc(derived);
}
BaseFunc operator()
DerivedFunc operator()

In this example, BaseFunc is the base functor class, and DerivedFunc is a derived class that overrides the operator().

The CallFunc function accepts a reference to a BaseFunc object and calls its operator(). When a DerivedFunc object is passed to CallFunc, the overridden operator() in DerivedFunc is called instead of the one in BaseFunc.

This demonstrates the polymorphic behavior of functors in an inheritance hierarchy.

Some key points to note:

  • The operator() in the base class is declared as virtual to enable polymorphism.
  • The operator() in the derived class is marked with override to indicate that it is overriding the base class's operator().
  • The CallFunc function accepts a reference to the base functor class, allowing it to work with both the base and derived functor objects.

Functor inheritance can be useful when you need to create a family of related functors with slight variations in their behavior. The base functor class can define the common interface and default behavior, while derived functors can override or extend the base behavior as needed.

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++?
Non-Operator Overloads in Functors
Can a functor class contain non-operator overloads, and how do I call them?
Templated operator() in Functors
Can the operator() in a functor be a template function?
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