You can use dynamic_pointer_cast
. It is supported by std::shared_ptr
.
std::shared_ptr<Base> base (new Derived());
std::shared_ptr<Derived> derived =
std::dynamic_pointer_cast<Derived> (base);
Documentation: https://en.cppreference.com/w/cpp/memory/shared_ptr/pointer_cast
Also, I don’t recommend using cast operator in the base class. Implicit casting like this may become the source of bugs and errors.
-Update: If the type is not polymorphic, std::static_pointer_cast
may be used.