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 asvirtual
to enable polymorphism. - The
operator()
in the derived class is marked withoverride
to indicate that it is overriding the base class'soperator()
. - 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.