jeudi 21 juillet 2016

How to initialize member in abstract class with std::function in which pure virtual member is called?

Here is the problem:

I have a class called Object, whose constructor accepts a std::function like this:

class Object {
 public:
  Object(std::function<void(Param* param)>) { ... }
};

Then an abstract base class and several derived classes like this:

class AbstractBase {
 public:
  AbstractBase() {
    // How to initialize object.
  }
  virtual string toString() const = 0;

 private:
  Object object;
};

class Derived1 : public AbstractBase {
 public:
  string toString() const override { return "Derived1"; }
}

class Derived2 : public AbstractBase {
 public:
  string toString() const override { return "Derived2"; }
}

I am trying to initialize the object in AbstractBase like this:

AbstractBase()
    : object([this](Param* param) {
        // do something
        param->addString(toString());
        // 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?

Aucun commentaire:

Enregistrer un commentaire