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 protected destructor?

A protected destructor is used to prohibit from the memory allocation on stack or in the static data segment and from the explicit deallocation by delete. I.e. an object can be created on the heap but delete cannot be called for its pointer.

Practical use of the protected destructor (usually it's also virtual):

  • base classes with object count variable
  • classes used in the environment with memory garbage collection
  • any other classes where explicit object deletion is not acceptable

class TestClass
{
public:
   TestClass() {}
   void Release()
   {
      //whatever required
      delete this;
   }

protected:
   virtual ~TestClass() {}
};

int main(int argc, char** argv[])
{
//   TestClass tc; // gives error C2248: 'TestClass::~TestClass' : cannot access
                   // protected member declared in class 'TestClass'

   TestClass* pTC = new TestClass;

//   delete pTC; // gives the same error

   pTC->Release();
   return 0;
}

Created: 2004-02-04
Updated: 2004-08-29

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