Program To Demonstrate Use Of Virtual Destructors In C++

LEVEL: Beginner

Whats in this post?

  1. Code
  2. Output
  3. Background and Explanation of the code

Code


To copy code: Click View Source “View Source” on the right of this code snippet.


Background and Explanation of the code


In this program the statement delete ptr; in the main ( ) invokes the derived class’s destructor as compiler dynamically binds to the destructor , depending upon the object to which base class ptr point.(Currently ptr points to derive’s object). After executing the derive class destructor ,the base class destructor is executed as destructors are executed in the reverse order of execution in inheritance.

Thus any memory allocated using the derived class constructor is freed.

OUTPUT

Base constructor

Derive constructor allocating 10 bytes of memory

Derive destructor frees 10 bytes of memory

Base destructor