4.2 Virtual destructor

We can make destructors virtual. Let us read the code in listing 6.


Listing 6:virtualdestructor
 
1class A 
2{ 
3  public
4    virtual ˜A(void{ cout << ”A::˜A(void)” << endl; } 
5}
6 
7class B 
8{ 
9  public
10    virtual ˜B(void{ cout << ”B::˜B(void)” << endl; } 
11}
12 
13void test(void
14{ 
15  A *pA = new B; 
16  delete pA; 
17}

The output of this program is "B::~B(void)", followed by "A::~A(void)". This means class B gets to execute its destructor, which in return invokes the destructor of class A implicitly (but after B::~B(void) is done).

This is much better than the non-virtual case. This time, a dynamically allocated object of class B gets to call the destructor specific to B. This destructor may contain code to clean up data members that are specific to class B.