Search code examples
c++vectorshared-ptrderived-class

Vector of shared_ptr resulting in error: "no instance of overloaded function" when wanting to push_back vector list


I have a smart pointer of a base class to prevent object slicing like so:

vector<shared_ptr<BaseClass>> vectorOfObjects;

I want to pass this object through a function and then add a derived object to the vector list:

function(vector<shared_ptr<BaseClass>>& vectorOfObjects) {}

In this function, I create a new derived object that I want to add to the list:

DerivedClass derivedObject = DerivedClass();

vectorOfObjects.push_back(&derivedObject);

I'm getting an error under the dot of the last line above stating

no instance of overloaded function std::vector<_Ty,_Ax>::pushback
 [with _Ty="std::tr1::shared_ptr<BaseClass>,_Ax=std::allocator<std:
:tr1::shared_ptr<BaseClass>>]" matches the argument list

Any help at all would be much appreciated as I can't seem to find the right solution to pass a vector consisting of a pointer of objects (required to prevent object slicing) through a function.


Solution

  • Use

    // DerivedClass derivedObject = DerivedClass(); <<< Not needed
    vectorOfObjects.push_back(std::make_shared<DerivedClass>());
    

    There's a number of constructor declarations that allow conversion from a std::shared_ptr<DerivedClass> to std::shared_ptr<BaseClass>.


    As from your comment

    If I need to make a separate declaration, as I also have a vector member in my BaseClass, how can I declare a derivedObject separately as I have attempted earlier?

    It's not completely clear for me what "as I also have a vector member in my BaseClass" has to do with it, but if you insist you can do:

    DerivedClass derivedObject* = new DerivedClass();
    // Do special stuff only available in DerivedClass
    derivedObject->specialFunc();
    vectorOfObjects.push_back(std::shared_ptr<DerivedClass>(derivedObject));