Here is the problem:
I have a class called Object
, whose constructor accepts a std::function
like this:
#include <functional>
#include <iostream>
#include <memory>
#include <string>
class Object {
public:
Object(std::function<void(int param)> f) : func(f) {}
~Object() { func(0); }
private:
std::function<void(int param)> func;
};
Then an abstract base class and several derived classes like this:
class AbstractBase {
public:
AbstractBase() {
// How to initialize object.
}
virtual std::string toString() const = 0;
private:
Object object;
};
class Derived1 : public AbstractBase {
public:
std::string toString() const override { return "Derived1"; }
}
class Derived2 : public AbstractBase {
public:
std::string toString() const override { return "Derived2"; }
}
I am trying to initialize the object
in AbstractBase
like this:
AbstractBase()
: object([this](int param) {
// do something
std::cout << toString() << std::endl;
// do something
}) {}
It compiles successfully, but raises "pure virtual method called" when AbstractBase
is deleted. So how can I initialize object
in the AbstractBase
and make sure toString
from derived class is called in the std::function
?