C++ Class Destructor Introduction

Introduction

A constructor is a member function that gets invoked when the object is initialized.

Similarly, a destructor is a member function that gets invoked when an object is destroyed.

The name of the destructor is tilde ~ followed by a class name:

class MyClass 
{ 
public: 
    MyClass() {}    // constructor 
    ~MyClass() {}   // destructor 
}; 

Destructor takes no parameters, and there is one destructor per class. Example:

#include <iostream> 

class MyClass //from   www  .j  a v  a 2 s.  c o  m
{ 
public: 
    MyClass() {}    // constructor 
    ~MyClass() 
    { 
        std::cout << "Destructor invoked."; 
    }    // destructor 
}; 

int main() 
{ 
    MyClass o; 
}   // destructor invoked here, when o gets out of scope 

Destructors are called when an object goes out of scope or when a pointer to an object is deleted.

We should not call the destructor directly.

Destructors can be used to clean up the taken resources.

Example:

#include <iostream> 

class MyClass /*from   w  w w.j  ava  2  s.  com*/
{ 
private: 
    int* p; 
public: 

    MyClass() 
         : p{ new int{123} } 
    { 
        std::cout << "Created a pointer in the constructor." << '\n'; 
    } 
    ~MyClass() 
    { 
        delete p; 
        std::cout << "Deleted a pointer in the destructor." << '\n'; 
    } 
}; 

int main() 
{ 
    MyClass o; // constructor invoked here 
} // destructor invoked here 

Here we allocate memory for a pointer in the constructor and deallocate the memory in the destructor.

This style of resource allocation/deallocation is called RAII or Resource Acquisition is Initialization.

Destructors should not be called directly.




PreviousNext

Related