Namespaces
Variants
Views
Actions

Destructors

From cppreference.com
 
 
C++ language
General topics
Preprocessor
Comments
Keywords
ASCII chart
Escape sequences
History of C++
Flow control
Conditional execution statements
Iteration statements
Jump statements
Functions
function declaration
lambda function declaration
function template
inline specifier
exception specifications (deprecated)
noexcept specifier (C++11)
Exceptions
Namespaces
Types
decltype specifier (C++11)
Specifiers
cv specifiers
storage duration specifiers
constexpr specifier (C++11)
auto specifier (C++11)
alignas specifier (C++11)
Literals
Expressions
alternative representations
Utilities
Types
typedef declaration
type alias declaration (C++11)
attributes (C++11)
Casts
implicit conversions
const_cast conversion
static_cast conversion
dynamic_cast conversion
reinterpret_cast conversion
C-style and functional cast
Memory allocation
Classes
Class-specific function properties
Special member functions
Templates
class template
function template
template specialization
parameter packs (C++11)
Miscellaneous
Inline assembly
 

A destructor is a member function that gets called each time an object goes out of scope or is deleted from memory. The purpose of the destructor is to free resources that the object may have acquired during its lifetime.

If not defined by the user, the compiler will generate one.

[edit] Syntax

~ClassName ( ) ;
virtual ~ClassName ( ) ;

[edit] Example

#include <iostream>
 
struct A
{
    int i;
 
    A ( int i ) : i ( i ) {}
 
    ~A()
    {
        std::cout << "~a" << i << std::endl;
    }
};
 
int main()
{
    A a1(1);
    A* p;
 
    { // nested scope
        A a2(2);
        p = new A(3);
    } // a2 out of scope
 
    delete p; // calls the destructor of a3
}

Output:

~a2
~a3
~a1