Polymorphism with Shared Pointers

How do shared pointers handle polymorphism? Can I store derived class objects in a shared_ptr of base class type?

Yes, shared pointers support polymorphism. You can store a derived class object in a shared_ptr of base class type. This is a key feature of shared pointers (and unique pointers) that distinguishes them from std::auto_ptr (which is now deprecated).

Consider this class hierarchy:

class Base {
public:
  virtual void foo() {
    std::cout << "Base::foo\n";
  }
};

class Derived : public Base {
public:
  void foo() override {
    std::cout << "Derived::foo\n";
  }
};

You can create a shared_ptr<Base> that points to a Derived object:

std::shared_ptr<Base> ptr =
  std::make_shared<Derived>();
ptr->foo();
Derived::foo

The virtual function call works as expected, calling Derived::foo even though ptr is a shared_ptr<Base>.

Moreover, when the last shared_ptr owning the object is destroyed, the object will be correctly deleted through the base class destructor, even if that destructor is virtual (which it should be for any polymorphic base class).

This is because shared_ptr uses type-erasure to store the deleter function. When you create a shared_ptr<Derived>, it will store a deleter that calls ~Derived(). When you assign this to a shared_ptr<Base>, the deleter is also copied. So even though the shared_ptr<Base> doesn't know about ~Derived(), the deleter still does.

This allows for safe and convenient use of polymorphism with shared pointers.

Shared Pointers using std::shared_ptr

An introduction to shared memory ownership using std::shared_ptr

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

Deleting a Shared Pointer Twice
What happens if I manually delete a shared pointer twice using the delete keyword?
Creating a shared_ptr to this
Is it okay to create a shared_ptr from the this pointer?
Shared Pointers in Multithreaded Environments
Are shared pointers thread-safe? Can they be used in multithreaded applications?
Shared Pointer Cyclic References
What happens if two shared pointers reference each other? Will this cause a memory leak?
When to Use Shared Pointers
In what situations should I use shared pointers instead of unique pointers or raw pointers?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant