I'm trying to figure out the tricks of class inheritance in C++ and I've built a sample project:
#include "stdafx.h"
#include <iostream>
using namespace std;
class A
{
public:
A()
{
cout << "Class A initialized" << endl;
}
~A()
{
cout << "Class A destructed" << endl;
}
};
class B : public A
{
public:
B()
{
cout << "Class B initialized" << endl;
}
~B()
{
cout << "Class B destructed" << endl;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
cout << "A* a = new A()" << endl;
A* a = new A();
cout << "B* b = new B ()" << endl;
B* b = new B ();
cout << "A* ab = new B()" << endl;
A* ab = new B();
cout << "delete a" << endl;
delete a;
cout << "delete b" << endl;
delete b;
cout << "delete ab" << endl;
delete ab;
int i;
cin >> i;
return 0;
}
The output I get is:
A* a = new A()
Class A initialized
B* b = new B ()
Class A initialized
Class B initialized
A* ab = new B()
Class A initialized
Class B initialized
delete a
Class A destructed
delete b
Class B destructed
Class A destructed
delete ab
Class A destructed
I can understand the behavior of class B as a derived class - first it constructs the base class and then the derived class. When it calls the destructor, it does the work the other way around. Seems logical.
What I can't understand, is the behavior of ab (allocation of B which I put into an A pointer), why does the constructor act the same as pure B, but the destructor runs only on A?
Thanks.