I have the following code:
class A { public: A() { cout << "A-C" << endl; } ~A(){ cout << "A-D" << endl; } }; class B { public: B() { cout << "B-C" << endl; } ~B() { cout << "B-D" << endl; } }; class C { protected: A* a; B b; public: C() { a = new A; cout << "C-C" << endl; } ~C() { delete a; cout << "C-D" << endl; } }; class D : public C { protected: A a; B b; public: D(){ cout << "D-C" << endl; } ~D(){ cout << "D-D" << endl; } }; int main() { D* d = new D; B* b = new B; delete b; delete d; system("pause"); return 0; } My initial thoughts on the output were:
A-C C-C A-C B-C D-C B-C B-D D-D B-D A-D A-D C-D But it's wrong. The output is actually:
B-C A-C C-C A-C B-C D-C B-C B-D D-D B-D A-D A-D C-D B-D I don't know why the program calls the B's constructor firstly and its destructor lastly. I think the order of constructor call should like this: C's constructor-> A's constructor -> B's constructor -> D's constructor.
And the order of destructor call is the reverse order of constructor call
Anyone can tell me the reason why the B's constructor is called at the beginning and B's destructor is called at last?
B-Cfirst?new Dcalls theCconstructor which calls theAconstructor.Chas aBdata member that's initialized before the constructor's body.Bdata member inCwas a pointer, my bad.