class Base {
public:
virtual void f() const { std::cout << "Base::f()" << std::endl; }
};
class Derived : public Base {
public:
void f() const { std::cout << "Derived::f()" << std::endl; }
};
int main()
{
Base* obj = new Derived;
std::shared_ptr<Base> sp = std::make_shared<Base>(*obj);
sp->f(); //prints Base::f()
}
What i expect is that sp->f()
prints Derived::f()
, just like raw pointers with virtual methods.
What is the correct way to have a polymorphic behaviour with std::shared_ptr
?
sp
points to an instance of type Base
, not Derived
. You can't clone derived classes using a pointer to base like this.
std::shared_ptr<Base> sp = std::make_shared<Derived>();
would work. ... =std::make_shared<Derived>(std::dynamic_cast<Derived&>(*obj))
would also work;