Can someone explain this interaction to me? (C++)

Posted by Nicenamebtw@reddit | learnprogramming | View on Reddit | 5 comments

#include <iostream>
using namespace std;


class A
{
public:
    A() { cout << "A constructor" << endl; }
    ~A() { cout << "A destructor;" << endl; }
    virtual void print() const
    {
        cout << "A print." << endl;
    }
};


class B : public A
{
public:
    B() { cout << "B constructor" << endl; }
    ~B() { cout << "B destructor" << endl; }
    void print() const override
    {
        cout << "B print" << endl;
    }
};


int main()
{
    A *a = new B;
    a->print();
    delete a;
}#include <iostream>
using namespace std;


class A
{
public:
    A() { cout << "A constructor" << endl; }
    ~A() { cout << "A destructor" << endl; }
    virtual void print() const
    {
        cout << "A print." << endl;
    }
};


class B : public A
{
public:
    B() { cout << "B constructor" << endl; }
    ~B() { cout << "B destructor" << endl; }
    void print() const override
    {
        cout << "B print" << endl;
    }
};


int main()
{
    A *a = new B;
    a->print();
    delete a;
}

Output:

A constructor
B constructor
B print
A destructor

I understand why the object is created as an object of B class, since 'new' invokes the constructor of class B. But I don't understand why only the destructor for A is called and not for B. Please explain, I would love to understand the logic behind this.