Search code examples
c++virtual-destructor

C++ Virtual Destructors in a 4 level inheritance chain.


I was doing a little experiment with virtual destructors to review - wondering if anyone has a simple explanation for the following (using vs 2010):

I Define class hierarchy A-B-C-D, D inherits C, C inherits B, B inherits A, A is the Base;

ran 2 experiments:

First experiment -

A has a virtual Destructor.

B has a non-Virtual Destructor

C has a virtual Destructor

D has a non virtual Destructor

//----------------------------

Allocate 4 objects on the heap of type D - Point a pointer of A*, B* and C* at the first 3 - Leave the 4th as a D* for Completeness. Delete all 4 Pointers.

As I expected, in all 4 instances, the complete destructor chain is executed in reverse order from D down to A, freeing all memory.

Second Experiment -

A has a non-virtual Destructor ** Changed A to non virtual

B has a non-Virtual Destructor

C has a virtual Destructor

D has a non virtual Distructor

Allocate 4 objects on the heap of type D - Point a pointer of A*, B*, and C* at the first 3 - Leave the 4th as a D* for Completeness.

Deleting C* and D* pointers: the complete destructor chain is executed in reverse order from D down to A, freeing all memory.

Deleting B*: B and then A Destructor is run (leak)

Deleting A*: Only A Destructor is run (leak)

Can anyone explain Why this is?

When D type opjects are allocated in experiment 2, its immediate base class (C) has a virtual destructor - doesnt that tell the compiler to track it with a Vptr and know the memory type? REGARDLESS of the reference?

Thanks Mike


Solution

  • When D type opjects are allocated in experiment 2, its immediate base class (C) has a virtual destructor - doesnt that tell the compiler to track it with a Vptr and know the memory type? REGARDLESS of the reference?

    No.

    In your second test case, A and B don't have vptrs/vtables. (And even if they did, a non-virtual member function would still be resolved statically, not dynamically.)

    Put another way, a base class does not "inherit" information (such as whether functions are virtual) from derived classes.