+ 2
Order of calling constructor and destructor: BDDB vs DBBD
class A { public: A() { cout <<"a";} ~A() { cout <<"b";} }; class B{ public: B() { cout <<"c";} ~B() { cout <<"d";} }; int main() { B b; A a; } // outputs cabd Since object b of class B is sequentially executed before object a of class A, class B's constructor is executed first. Next the confusion kicks in... Why does class A's constructor get executed before class B's destructor? Class A and class B do NOT have an inheritance relationship, so wouldn't it make sense to free the memory for the instance of class B ASAP? Is it a general rule to finish executing all constructors (in the order of class instances being allocated memory) before executing destructors?
1 Réponse