C++ examples for Class:Destructor
Member object destructors are called for only those member objects that were constructed before an exception occurred.
#include <iostream> #include <stdexcept> class C1 {//w ww.j a v a 2 s .c om public: C1() { std::cout << "C1 Constructor" << std::endl; } ~C1() { std::cout << "C1 Destructor" << std::endl; } }; class C2 { public: C2() { std::cout << "C2 Constructor" << std::endl; } ~C2() { std::cout << "C2 Destructor" << std::endl; } }; class C3 { public: C3() { std::cout << "C3 Constructor" << std::endl; C1 c1; throw std::exception(); C2 c2; } ~C3() { std::cout << "C3 Destructor" << std::endl; } }; int main(int argc, const char *argv[]) { try { C3 c3; } catch (std::exception &e) { std::cout << "exception: " << e.what() << std::endl; } return 0; }