// Illustration of non-virtual destructors. Motivation for next version of the program. // The B-object pointed to by a1 is not properly destructed. #include using namespace std; class A { private: double a; public: A(double a): a(a){}; ~A(){cout << "A destructor" << endl;} // Non-virtual destructor // Class A is assumed to have virtual functions. //.... }; class B : public A { private: double b; public: B(double b): A(b-1), b(b){}; ~B(){cout << "B destructor" << endl;} //... }; void e(){ cout << "Now start of e" << endl; B b1(6.0); // b1 contains a B object // Work on b1. cout << "Now end of e" << endl; // b1 goes out of scope. It is destructed at both B and A level. } void f(){ cout << "Now start of f" << endl; A *a1 = new B(5.0); // a1 points to a B object on the free store. // Work on a1 delete a1; // The destructor in A called // The B destructor is not called. May cause problems (leaking). // The destructor in A is not virtual. cout << "Now end of f" << endl; } int main(){ e(); cout << endl << endl; f(); }