How to cast a vector of shared_ptrs of a derived class to a vector of share_ptrs of a base class

c++, stl

Solution

Casting is not correct, they are distinct types; I am pretty certain you are invoking undefined behaviour.

You need to construct a new vector and return it by value.

std::vector<std::shared_ptr<Interface>> b (m_data.begin(), m_data.end());
return b;

This should still be fairly cheap (1 allocation).

Problem

``` class Interface { }; class Class : public Interface { }; class Foo { public: std::vector<std::shared_ptr<Interface>>& GetInterfaces() { return *(std::vector<std::shared_ptr<Interface>>*)(&m_data); //return m_data; } private: std::vector<std::shared_ptr<Class>> m_data; }; ``` This works but is ugly and scary. Is there a better/safer way to do it? I don't want to make `m_data` of type `std::vector<std::shared_ptr<Interface>>` because the module `Foo` belongs to works entirely with `Class`'s, `Interface` (and `Foo::GetInterfaces()`) are implemented to interact with a separate module that should only know about the `Interface` functionality. Let me know if anything here is unclear, it makes sense to me but I've been banging my head against the problem for a while.

Original source