Back to slide -- Keyboard shortcut: 'u'  previous -- Keyboard shortcut: 'p'  next -- Keyboard shortcut: 'n'          destructors-inheritance/prog4.cc - Base class A and derived class B and C with virtual destructors.Lecture 5 - slide 8 : 40
Program 5

// Not much new stuff here. Illustration of virtual destructors in A-B-C class hierarcy. 
// Shows that we only need to declare a virtual destructor in the base class. 

#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;}
  //...
};

class C : public B {
private:
  double c;
public:
  C(double b): B(b-1), c(b){};
  ~C(){cout << "C destructor" << endl;}
  //...
};

void f(){
  A *a1 = new C(5.0);
  
  // Work on a1
  // ....

  delete a1;                        // The destructor in C is called.
                                    // The destructor in B is called.
                                    // The destructor in A is called.
}  

int main(){
  f();
}