tadge
tadge

Reputation: 96

returning std::shared_ptr<Derived> from vector of std::shared_ptr<Base>

I have an std::vector of shared_ptr<Base> which contains many shared_ptr<Derived> objects. As a property of Base, each object has a string name for various reasons. I have a function std::shared_ptr<Base> GetObjectByName(const char* name) where I want to be able to return a derived component by evaluating if its name is the object Im looking for. What is the best way to get the std::shared_ptr<Derived> from the std::vector<std::shared_ptr<Base>>

Upvotes: 0

Views: 78

Answers (1)

Andrey Semashev
Andrey Semashev

Reputation: 10614

Assuming that Base and Derived are polymorphic (i.e. have at least one virtual function), you can use std::dynamic_pointer_cast:

std::shared_ptr<Base> pBase = GetObjectByName("name");
std::shared_ptr<Derived> pDerived = std::dynamic_pointer_cast<Derived>(pBase);

Upvotes: 1

Related Questions