Go back to Richel Bilderbeek's homepage.

Go back to Richel Bilderbeek's C++ page.

 

 

 

 

 

(C++) Destructor

 

A destructor is a class element that is called when a class goes out of scope. The class element that is called when a class is created is called the constructor.

 

#include <iostream>

struct MyClass
{
  ~MyClass() { std::cout << "Destructor\n"; }
};

int main()
{
  MyClass m;
} //MyClass destructor called at end of main

 

 

All base classes must have a (public) virtual destructor. A non-base class should have a (non-public) non-virtual destructor [1,3].

 

Avoid calling virtual member functions in constructors and destructors [2].

 

 

 

 

 

References

 

  1. Herb Sutter, Andrei Alexandrescu. C++ coding standards: 101 rules, guidelines, and best practices. ISBN: 0-32-111358-6. Item 50: 'Make base class destructors public and virtual, or protected and nonvirtual'.
  2. Herb Sutter, Andrei Alexandrescu. C++ coding standards: 101 rules, guidelines, and best practices. 2005. ISBN: 0-32-111358-6. Item 49: 'Avoid calling virtual functions in constructors and destructors'
  3. Joint Strike Fighter Air Vehicle C++ Coding Standards for the System Development and Demonstration Program. Document Number 2RDU00001 Rev C. December 2005. AV Rule 78: 'All base classes with a virtual function shall define a virtual destructor.'

 

 

 

 

 

Go back to Richel Bilderbeek's C++ page.

Go back to Richel Bilderbeek's homepage.

 

Valid XHTML 1.0 Strict