The code did not compile as written. Make sure to copy the code exactly as it is from the editor. You know what the output is, so there is no excuse for these little mistakes in the code on the board.
You know you constructed one object, right?
B *b = new B(5);
The A pointer allows you to access the B part of the object polymorphically. So when you call
a->Add(c); the function invoked is actually B::Add(int n). When the destructor is called, the B part is actually destroyed first, then the A part.
That's all that happens in your code too. The output is just confusing. If we change the code slightly it might be clearer. I propose new destructors:
Code:
virtual ~A()
{
cout << "A destructor " << endl;
cout << "...x: " << x << endl;
}
~B()
{
cout << "B destructor " << endl;
std::cout <<"...y: " << y << "...z: " << z << endl;
}
Now the output is:
A constructor
B constructor
B destructor
...y: 1...z: 1
A destructor
...x: 0
Now that you know what members are from what objects, does it make more sense how the object is deleted now?