![]() ![]() ![]() | Base class A and derived class B with non-virtual destructors - motivation. | Lecture 4 - slide 6 : 24 Program 1 |
// Illustration of non-virtual destructors. Motivation for next version of the program. #include <iostream> using namespace std; class A { private: double a; public: A(double a): a(a){}; ~A(){cout << "A destructor" << endl;} // 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 f(){ A *a1 = new B(5.0); // a1 points to a B object on the free store. B b1(6.0); // b1 contains a B object // Work on a1 and b1. // .... delete a1; // The destructor in A called // The B destructor is not called. LEAK and PROBLEMS. // The destructor in A is not virtual. cout << "Now end of f" << endl; // B destructor (object b1) // b1 goes out of scope. It is destructed at // A destructor (object b1) // ... both B and A level. } int main(){ f(); }