Home > front end >  Downcasting to base type of vector of shared_ptr
Downcasting to base type of vector of shared_ptr

Time:10-26

#include <vector>
#include <memory>

class Base {
public:
    virtual ~Base() = default;
    virtual int f() = 0;
};

class Derived : public Base {
public:
    ~Derived() = default;
    int f() override { return 0; }
};

int main() {

const std::vector<std::shared_ptr<const Base>> vec{std::make_shared<const Derived>()};

}

failed at compile time, then at link time, when I originally posted it here with two mistakes in the code.

Too late to delete; no way to revert to the initial form. Hence let it stay as a minimal example to demonstrate that a vector of a shared_ptr can have a polymorphic base type.

I have seen other questions touching this topic, with answers suggesting we need a pure virtual base class. Hence the virtual destructor and the pure virtual function in the above minimal example.

CodePudding user response:

There is no problem with having a polymorphic type here, but you need to explicitly say that std::make_shared<const Derived>() is supposed to be an element, and not an argument of some fancy constructor.

std::vector doesn't have any constructor that takes a single std::shared_ptr, but you can redirect the name lookup with use of curly braces initialisation syntax (it gives priority to std::initialiser_list constructors, and treats the enclosed objects as elements):

const std::vector<std::shared_ptr<const Base>> vec{ std::make_shared<const Derived>(); }
  • Related