![]() ![]() ![]() ![]() | Base class A and derived class B with virtual destructors. | Lecture 4 - slide 6 : 24 Program 3 |
// Illustration of virtual destructors. #include <iostream> using namespace std; class A { private: double a; public: A(double a): a(a){}; virtual ~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); B b1(6.0); // Work on a1 and b1. // .... delete a1; // The destructor in B is called. // The destructor in A is called. cout << "Now end of f" << endl; // B destructor (object b1) // A destructor (object b1) } int main(){ f(); }