4.1 Non-virtual destructor

Let us consider the case of a static destructor in listing 5.


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

When test is called, it prints "A::~A(void)". This is because the destructor is not virtual. As a result, the compiler chooses the destructor based on compile-time information, which says pA points to a class A object.

Note that this is not always a problem. The storage allocated is safely deallocated, and for the most part, things are cleaned up. In our example code, it makes little difference anyway.

However, if a class B object has its own private dynamically created objects (like a linked list), then the destructor of A will not deallocate those objects. As a result, sometimes we need to make a destructor stick with the object.