Shared Pointers using std::shared_ptr

Polymorphism with Shared Pointers

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

Illustration representing computer hardware

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.

Answers to questions are automatically generated and may not have been reviewed.

A computer programmer
Part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

  • 124 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved