I have the following C++ program :
#include <iostream>
using namespace std;
class A
{
public:
A()
{
cout << "A constructor" << endl;
}
~A()
{
cout << "A destructor" << endl;
}
};
class B : public A
{
public:
B()
{
cout << "B constructor" << endl;
}
~B()
{
cout << "B destructor" << endl;
}
};
int main()
{
A a1;
A *a2 = new B();
delete a2;
}
On running the output is
A constructor
A constructor
B constructor
A destructor
A destructor
I don't understand the output.
A a1; --> this calls A constructor
A *a2 = new B();--> This should call A constructor which in turn should call B constructor
delete a2;
Now, in the end, I see two A destructor calls. But no B destructor call. Sinde the pointer a2 points to an object B. There should have been a call to B destructor before the program exits. What could be the reason that B destructor didn't get called?