Why std::shared_ptr calls destructors from base and derived classes, where delete calls only destructor from base class?

Viewed 9814

Why when using std::shared_ptr deallocation calls destructors from both base and derived classes when second example calls only destructor from base class?

class Base
{
public:
    ~Base()
    {
        std::cout << "Base destructor" << std::endl;
    }
};

class Derived : public Base
{
public:
    ~Derived()
    {
        std::cout << "Derived destructor" << std::endl;
    }
};

void virtual_destructor()
{
    {
        std::cout << "--------------------" << std::endl;
        std::shared_ptr<Base> sharedA(new Derived);
    }

    std::cout << "--------------------" << std::endl;
    Base * a = new Derived;
    delete a;
}

Output:

--------------------
Derived destructor
Base destructor
--------------------
Base destructor

I was expecting the same behaviour in both cases.

2 Answers
Related