C++ and STL
  Common Issues
  Destructor
  regex
  string
 MFC
  CButton
  CDialog
  CEdit
  CInternetSession
  CWinThread
  CWnd
 MS VS FAQ
  Compiling, building
  Debugging
  Editor
  Settings
 Win32, API
  Console
  File System
  Graphics
  Internet functions
  Kernel objects
  Security
  Sound
  Thread, process
  Window
 Windows NT/2K*
  Logon, logoff...
  Networking
  Service Packs
 | About
  About
  Links & Freeware

Powered by
CoderTown



Why do I need a virtual destructor?

A virtual destructor is an essential entity if you use inheritance. Virtual destructor is declared in a base class. It guarantees that for all classes derived from the base class all destructors: 1) will be called and 2) will be called in proper order. It makes available a polymorphic behavior. Take a look at the snippet below:

#include "stdio.h"

class BaseClass
{
	int id;
public:
	BaseClass() { printf("BaseClass()\n"); }
	virtual ~BaseClass() { printf("~BaseClass()\n"); } //    !!!
};

class Class1 : public BaseClass
{
	int id;
public:
	Class1() { printf("Class1()\n"); }
	~Class1() { printf("~Class1()\n"); }
};

class Class2 : public Class1
{
	int id;
public:
	Class2() { printf("Class2()\n"); }
	~Class2() { printf("~Class2()\n"); }
};


int main(int argc, char* argv[])
{
	BaseClass *p = new Class2;
	delete p;

	return 0;
}

The output in case without virtual destructor is:

BaseClass()
Class1()
Class2()
~BaseClass()

But the output in case with virtual destructor differs:

BaseClass()
Class1()
Class2()
~Class2()
~Class1()
~BaseClass()

Now you see what happens if destructor should call delete() for some object/array used in the class? Resume: use virtual destructor to ensure proper memory clearing in case of using inheritance.

Created: 2003-05-11
Updated: 2003-06-05

Google
 
Web visualcpp.net
msdn.microsoft.com codeguru.com