While experimenting with the concepts of object slicing and polymorphism, I came up with this code example, which works as I was expecting: the function call operator of the derived FunctorTrue
class is called -instead of that of the parent Functor
class.
#include <iostream>
#include <functional>
using namespace std;
class Functor : public std::function<bool()> {
public:
virtual ~Functor() {};
virtual bool operator()() const {return false;};
};
class FunctorTrue : public Functor{
public:
bool operator()() const {return true;}
};
class Dispatcher {
public:
const Functor & mFunctor;
Dispatcher(const Functor & functor): mFunctor(functor) {}
Dispatcher(const Functor && functor): mFunctor(functor) {
}
void dispatch(){
cout << boolalpha << mFunctor() << endl;
}
};
int main() {
Dispatcher dt = Dispatcher(FunctorTrue());
dt.dispatch(); // returns true
}
Note: You can run this example in Ideone.
I found out that if I modify the constructor of the Dispatcher
class to print out a line, the function call operator of the parent would be called instead:
class Dispatcher {
public:
const Functor & mFunctor;
Dispatcher(const Functor & functor): mFunctor(functor) {}
Dispatcher(const Functor && functor): mFunctor(functor) {
cout << "Constructor with rvalue" << endl;
}
void dispatch(){
cout << boolalpha << mFunctor() << endl;
}
};
int main() {
Dispatcher dt = Dispatcher(FunctorTrue());
dt.dispatch(); // returns false
}
Note: You can also run this example in Ideone.
That unexpected behavior led me to think that, because of the type of the member variable mFunctor
in the Dispatcher
class, the dispatch
method only knows about the "base class part" of the object, effectively calling the function call operator of the base class. But that doesn't hold true in the original example, which leaves me all confused.
My questions are:
1) Why does the change in the constructor changes the method being called in the Functor > FunctorTrue
class hierarchy?
2) If the variation is related to some optimization that the default constructor does, what is that optimization and how can I specify it?
Thanks a lot in advance.