Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is it possibile to call virtual methods with shared pointers?

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?

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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;

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading