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

// Illustration of virtual destructors. Now, the destructor of class A is virtual.

#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);
  
  // Work on a1

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

  cout << "Now end of f" << endl;
}  

int main(){
  f();
}