dynamic method binding in destructor (or lack thereof?)

Hello,

Could anyone shed light on any different static and dynamic binding rules during execution of a destructor? I expected that RTTI and dynamic binding would still occur, but the following toy program indicates otherwise:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
using namespace std;

class A {
   public:
      virtual void cleanup() {
         cout << "class A cleanup" << endl;
      }

      virtual ~A() { cleanup(); }
};

class B : public A {
   public:
      virtual void cleanup() {
         cout << "class B cleanup" << endl;
      }

      virtual ~B() { }
};

int main() {
   B  b;
   return 0;
}


The result:

class A cleanup

I expected that dynamic binding would occur and "class B cleanup" would be produced.

Have I done something wrong? Or have I expected something wrong?
First it calls ~B(), that does nothing. Then it calls its parent destructor ~A() (so it is threat as an parent object)
AFAIK you could only experiment polymorphism when you work with pointers/references
Last edited on
You cannot call virtual functions from a destructor (and expect the derived implementation to be called).



Ok. So, I can't expect the overriding method to be called. Thanks, jsmith.


K
Topic archived. No new replies allowed.