Search code examples
c++inheritancevectorunique-ptrpush-back

Vector push back a derived smart pointer into a vector of smart pointers of a base abstract class


Suppose I have the following base abstract classes

class Worker {
    public:
      struct Details {
           std::string name;
      };
    public:
      virtual void work() = 0;

};
class Manager {
    public: 
      virtual ~Manager() = default;
      virtual void hire(Worker::Details details) = 0;
      virtual void fire(const Worker & worker) = 0;
};

And then I have an implementation of both of these abstract classes:

class DerivedWorker : Worker {
    public:
      DerivedWorker(Worker::Details details) : details(details) {}
      
      void work() override {}
    private:
      Worker::Details details;
};
class Derived : Manager {
    public:
      Derived() {}
      void hire(Worker::Details details) override {
          workers.push_back(std::make_unique<DerivedWorker>(details));
      }
      void fire(const Worker & worker) override {}
    private:
      std::vector<std::unique_ptr<Worker>> workers;
};

Why does workers.push_back(std::make_unique<DerivedWorker>(details) throw a compiler error: no matching member function for call to 'push_back' exception?

Similarly, how would you do the same with workers.emplace_back(...)?


Solution

  • The push_back doesn't work because you forgot to make the inheritance public.

    Probably the same issue for emplace_back, though you should never use emplace_back for a vector of smart pointers.