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.
std::shared_ptr
An introduction to shared memory ownership using std::shared_ptr