Search code examples
c++vectorshared-ptr

Vector of shared_ptr of a abstract bass class pointing to derived classes


I am in a class where I am supposed to create a vector of shared pointers with an abstract base class and a two level hierarchy for derived classes.

class Base
{
   virtual string returnName() = 0;
};

class DerivedOne : public Base
{
private:
   string name;

public:
   DerivedOne()
   {name = "Derived";}

   virtual string returnName()
   {return name;}
};

class DerivedTwo : public DerivedOne
{
private:
   string secondName;

public:
   DerivedTwo()
   {secondName  = "DerivedTwo";}

   virtual string returnName()
   {return secondName;}
};

int main()
{
   vector<shared_ptr<Base>> entities;
   entities.push_back(new DerivedOne());

   return 0;
}

My issue is with adding a derived class to the end of the vector using the push_back() and when compiling it says no matching function for call to ‘std::vector<std::shared_ptr<Base> >::push_back(DerivedOne*)

How would I add an initialized derived class to the vector?


Solution

  • You should avoid using a raw new at all. Instead, you should use std::make_shared to allocate your objects that will be managed by std::shared_ptrs:

    entities.push_back(std::make_shared<DerivedOne>());
    

    std::make_shared returns a std::shared_ptr to the newly allocated object rather than a raw pointer. Not only that make std::vector::push_back work in this case, it's also less likely to leak memory in the face of exceptions.